如何从Action委托创建MethodInfo

我正在尝试开发一个NUnit插件,它从包含Action委托列表的对象动态地将测试方法添加到套件中。 问题在于NUnit似乎非常倾向于反思以完成工作。 因此,看起来没有简单的方法将Action直接添加到套件中。

相反,我必须添加MethodInfo对象。 这通常有效,但Action代理是匿名的,所以我必须构建完成此任务的类型和方法。 我需要找到一种更简单的方法来做到这一点,而不需要使用Emit 。 有谁知道如何从Action代理轻松创建MethodInfo实例?

你有没有尝试过Action的Method属性? 我的意思是:

 MethodInfo GetMI(Action a) { return a.Method; } 

您不需要“创建” MethodInfo ,只需从委托中检索它:

 Action action = () => Console.WriteLine("Hello world !"); MethodInfo method = action.Method 
 MethodInvoker CvtActionToMI(Action d) { MethodInvoker converted = delegate { d(); }; return converted; } 

对不起,不是你想要的。

请注意,所有委托都是多播的,因此不能保证是唯一的MethodInfo 。 这将为您提供所有这些:

 MethodInfo[] CvtActionToMIArray(Action d) { if (d == null) return new MethodInfo[0]; Delegate[] targets = d.GetInvocationList(); MethodInfo[] converted = new MethodInfo[targets.Length]; for( int i = 0; i < targets.Length; ++i ) converted[i] = targets[i].Method; return converted; } 

你丢失了有关目标对象的信息(解除了委托),所以我不希望NUnit能够在之后成功调用任何东西。