我有这个类(简化示例)
public class Foo
{
public object Bar(Type type)
{
return new object();
}
}
我想在using的实例上Bar
调用该方法,如下所示:Bar
DynamicMethod
MethodInfo methodInfo = typeof(Foo).GetMethod(nameof(Foo.Bar), new[] { typeof(Type) });
DynamicMethod method = new DynamicMethod("Dynamic Bar",
typeof(object),
new []{ typeof(Type) },
typeof(Foo).Module);
ILGenerator ilGenerator = method.GetILGenerator();
ilGenerator.Emit(OpCodes.Ldarg_0);
ilGenerator.EmitCall(OpCodes.Call, method, null); // I feel like this is wrong...
ilGenerator.Emit(OpCodes.Ret);
Func<Type, object> func = (Func<Type, object>) method.CreateDelegate(typeof(Func<Type, object>));
// Attempt to call the function:
func(typeof(Foo));
但是,它不能按预期工作,而是中止
进程因 StackOverFlowException 而终止。
有人可以告诉我我做错了什么吗?是不是参数不匹配?如何调用 的Func
特定实例Bar
?