public void TreatAs(Type clrTypeSrc, Type clrTypeDst)
{
// If source = destination, then no-op
if (clrTypeSrc == clrTypeDst)
return;
if (clrTypeSrc.GetTypeInfo().IsValueType)
{
// If source is a value type, then destination may only be typeof(object), so box
Debug.Assert(clrTypeDst == typeof(object), "Invalid cast, since value types do not allow inheritance.");
Emit(OpCodes.Box, clrTypeSrc);
}
else if (clrTypeDst.GetTypeInfo().IsValueType)
{
// If destination type is value type, then source may only be typeof(object), so unbox
Debug.Assert(clrTypeSrc == typeof(object), "Invalid cast, since value types do not allow inheritance.");
Emit(OpCodes.Unbox, clrTypeDst);
Emit(OpCodes.Ldobj, clrTypeDst);
}
else if (clrTypeDst != typeof(object))
{
// If source is not a value type, and destination type is typeof(object), then no-op
// Otherwise, use Castclass to change the static type
Debug.Assert(clrTypeSrc.IsAssignableFrom(clrTypeDst) || clrTypeDst.IsAssignableFrom(clrTypeSrc),
"Invalid cast, since source type and destination type are not in same inheritance hierarchy.");
Emit(OpCodes.Castclass, clrTypeDst);
}
}