如何调用从匿名方法创建的 MethodInfo?
在上一个问题中,我问如何从 Action 委托获取 MethodInfo
。此操作委托是匿名创建的(通过 Lambda)。我现在遇到的问题是我无法调用 MethodInfo
,因为它需要 MethodInfo
所属的对象。在这种情况下,由于代表是匿名的,因此没有所有者。我收到以下异常:
<块引用>System.Reflection.TargetException:对象与目标类型不匹配。
我正在使用的框架(NUnit)要求我使用反射来执行,所以我必须在提供的范围内进行操作。我真的不想仅仅为了执行我已有的委托而使用 Emit
创建动态程序集/模块/类型/方法。
谢谢。
In a previous question, I asked how to get a MethodInfo
from an Action delegate. This Action delegate was created anonymously (from a Lambda). The problem I'm having now is that I can't invoke the MethodInfo
, because it requires an object to which the MethodInfo
belongs. In this case, since the delegates are anonymous, there is no owner. I am getting the following exception:
System.Reflection.TargetException : Object does not match target type.
The framework I'm working with (NUnit) requires that I use Reflection to execute, so I have to play within the walls provided. I really don't want to resort to using Emit
to create dynamic assemblies/modules/types/methods just to execute a delegate I already have.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您已经获得了 Method 属性。您需要将 Target 属性作为第一个参数传递给 MethodInfo.Invoke()。
You already got the Method property. You'll need the Target property to pass as the 1st argument to MethodInfo.Invoke().
看起来 lambda 方法即使在静态上下文中声明,也被定义为实例方法。
解决方案:
It looks like that lambda methods, even when declared in a static context, are defined as instance methods.
Solution: