Equivalent to Expression.Convert using Reflection.Emit

719 Views Asked by At

I am currently trying to extent an existing application that uses reflection (ILGenerator) to create a dynamic method.

I currently have an object on the stack, this method needs to convert the object to the same type as 'parameterType'. I want to provide the same conversion functionality that we get when using Expression.Convert

public override void EmitParameterResolution(ILGenerator il, Type parameterType)
{
    // il.Emit - Not sure what to do here...
    // Expression.Convert(obj, parameterType)
} 
1

There are 1 best solutions below

1
On

You probably want Castclass:

public override void EmitParameterResolution(ILGenerator il, Type parameterType)
{
    il.Emit(OpCodes.Castclass, parameterType);
}

You might also think about just Call, put parameterType on the stack after obj and then do something like this:

MethodInfo mi = typeof(Convert).GetMethod("ChangeType");
il.Emit(OpCodes.Call, mi);