使用“方法”来自 Action的 MethodInfo 属性il.EmitCall 中的委托

发布于 2024-09-15 05:17:44 字数 356 浏览 1 评论 0原文

这样的事情可能吗?

//
//  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。

谢谢

Is something like this possible?

//
//  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);

Im getting a MethodAccessException whenever I try to invoke the method.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

晨敛清荷 2024-09-22 05:17:44

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

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

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

您需要执行以下任一操作:

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

Im getting a MethodAccessException whenever I try to invoke the method.

This is because the method generated for the C# (t) => t.DoSomething lambda is private. Chances are this lambda won't be static, either, depending on which of the local variables it captures from the outer method. You're issuing a callvirt instruction but you don't appear to be supplying an instance.

You can verify this by loading your application's code in Reflector and looking at the implementation of your (t) => t.DoSomething lambda.

You need to either:

  • Upgrade your lambda to a real public static method in an externally-visible class
  • Find a way to include a parameter of type Action<Type> in your IL method, generate code that calls Action<Type>.Invoke, then pass your action variable into the generated method
深陷 2024-09-22 05:17:44

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

See if this is related to what is mention Here.

安穩 2024-09-22 05:17:44

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

If you use a dynamic method you can use the skip visibility checks in the jitter.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文