这是对此处提供的解决方案的扩展。我创建了一个静态方法,返回一个对象。我的目标是为我在运行时定义的类型编写一个动态方法,使其返回这个静态方法返回的对象。到目前为止,我的代码如下:
// type builder and other prep stuff removed for sake of space and reading
private void EmitReferenceMethodBody(Type returnType)
{
MethodBuilder builder =
typeBuilder.DefineMethod(
method.Name,
MethodAttributes.Virtual | MethodAttributes.Public,
method.CallingConvention,
method.ReturnType,
typeArray1);
builder.InitLocals = true;
ILGenerator gen = builder.GetILGenerator();
MethodInfo getStoredObject = typeof(ObjectStore).GetMethod("GetStoredObject", BindingFlags.Public | BindingFlags.Static);
MethodInfo getTypeFromHandle = typeof(Type).GetMethod("GetTypeFromHandle");
gen.Emit(OpCodes.Ldtoken, returnType);
gen.Emit(OpCodes.Call, getTypeFromHandle);
gen.Emit(OpCodes.Call, getStoredObject);
gen.Emit(OpCodes.Ret);
}
更新后的代码调用了方法,但似乎传递的是动态创建类型的类型,而不是变量returnType。
object GetStoredObject(Type returnType);
。如果是这样,那么您确实需要传入一个参数。但是,您实际上要传递什么类型的参数? - Kirk Woll