使用il.EmitCall </t>中Action <t>委托的“Method”MethodInfo属性

时间:2010-08-19 08:14:37

标签: c# .net reflection.emit

这样的事情可能吗?

//
//  create a delegate
Action<Type> action = (t) => t.DoSomething;

//
// get the IL generator for a method
ILGenerator il = myMethodBuilder.GetILGenerator();

//
// try and call the delegate
il.EmitCall(OpCodes.Callvirt, action.Method, null);

每当我尝试调用该方法时,我都会收到MethodAccessException。

由于

3 个答案:

答案 0 :(得分:3)

  

每当我尝试调用该方法时,我都会收到MethodAccessException。

这是因为为C#(t) => t.DoSomething lambda生成的方法是私有的。有可能这个lambda也不会是静态的,这取决于它从外部方法捕获的局部变量。您正在发出callvirt指令,但您似乎没有提供实例。

您可以通过在Reflector中加载应用程序的代码并查看(t) => t.DoSomething lambda的实现来验证这一点。

您需要:

  • 将lambda升级为外部可见类
  • 中的真实public static方法
  • 找到在IL方法中包含Action<Type>类型参数的方法,生成调用Action<Type>.Invoke的代码,然后将action变量传递给生成的方法

答案 1 :(得分:0)

看看这是否与提到Here的内容有关。

答案 2 :(得分:0)

如果使用动态方法,则可以在抖动中使用跳过可见性检查。

相关问题