2010-04-05 100 views
7

我想开发一个NUnit插件,动态地将测试方法从包含Action代表列表的对象添加到套件。问题在于NUnit似乎严重依赖反思来完成工作。因此,看起来没有简单的方法将我的Action直接添加到套件中。我怎样才能从行动委托创建一个MethodInfo

相反,我必须添加MethodInfo对象。这通常会起作用,但Action委托人是匿名的,所以我将不得不构建类型和方法来完成此操作。我需要找到一个更简单的方法来做到这一点,而不是诉诸于使用Emit。有谁知道如何轻松地从Action代理创建MethodInfo实例?

回答

10

你试过操作的方法的财产?我的意思是这样的:

MethodInfo GetMI(Action a) 
{ 
    return a.Method; 
} 
1
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; 
} 

你失去约虽然(uncurrying委托)的目标对象的信息,所以我不希望NUnit的是随后能够成功调用任何东西。

+0

这将产生一个编译时错误... – Aaronaught 2010-04-05 02:36:41

+0

对不起,我在想MethodInvoker的,当我看到的MethodInfo。 – 2010-04-05 03:43:26

+0

+1(让你回到零)。事实证明,d.Method是我所需要的。它在NUnit中工作,虽然命名很时髦。我将不得不创建自己的测试课来解决这个问题。 – 2010-04-05 10:26:13

3

你并不需要“创造” MethodInfo,你可以从委托检索:

Action action =() => Console.WriteLine("Hello world !"); 
MethodInfo method = action.Method 
+2

+1,你和Fede都有正确的答案。我接受了他,因为他的代表队中有两位数较少的领带。 :) – 2010-04-05 10:23:28