2010-04-05 86 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