2016-09-01 87 views
2

我需要做一個方法來檢查作爲參數傳遞的動態方法委託。但是我不能強迫表達樹接受任何方法,而不管它們的簽名。ExpressionTree作爲方法參數來接受任何方法

這是我的方法(不編譯:error CS0030: Cannot convert type 'method' to 'Delegate'

public void Examine<T>(Expression<Func<T, Delegate>> expression2) 
{ 
    // examine expression tree to get method name (MethodInfo) 
} 

我想這樣調用它:

Examine<Foo>(x => foo1.Test1); 
Examine<Bar>(x => bar2.DifferentMethod2); 
// etc, with other methods 

其中:

  • 類Foo有方法:bool Test1(int num)
  • class Bar has method:'string DifferentMethod2(字符串,字符串二)`
  • 和許多其他

如何實現的呢?

備註:

  • 我不能使用Func鍵<>或行動<>一樣會有需要與參數類型可以接受許多可能的方法簽名,我不會有一個參考。
+0

還沒有測試過,但func或動態動態?庸醫像鴨子一樣 –

回答

4

你必須使用FuncAction,但是你可以使用它在發送方,而不是方法方面,所以你還是可以接受任何類型。

static void Main() 
{ 
    Foo foo1 = null; 
    Bar bar2 = null; 
    Examine<Foo>(x => (Func<int,bool>)foo1.Test1); 
    Examine<Bar>(x => (Func<string,string,string>)bar2.DifferentMethod2); 
} 
public static void Examine<T>(Expression<Func<T, Delegate>> expression2) 
{ 
    // examine expression tree to get method name (MethodInfo) 
} 

這產生像

.Lambda #Lambda1<System.Func`2[SandboxConsole.Foo,System.Delegate]>(SandboxConsole.Foo $x) { 
    (System.Func`2[System.Int32,System.Boolean]).Call .Constant<System.Reflection.MethodInfo>(Boolean Test1(Int32)).CreateDelegate(
     .Constant<System.Type>(System.Func`2[System.Int32,System.Boolean]), 
     .Constant<SandboxConsole.Program+<>c__DisplayClass0_0>(SandboxConsole.Program+<>c__DisplayClass0_0).foo1) 
} 

.Lambda #Lambda1<System.Func`2[SandboxConsole.Bar,System.Delegate]>(SandboxConsole.Bar $x) { 
    (System.Func`3[System.String,System.String,System.String]).Call .Constant<System.Reflection.MethodInfo>(System.String DifferentMethod2(System.String, System.String)).CreateDelegate(
     .Constant<System.Type>(System.Func`3[System.String,System.String,System.String]), 
     .Constant<SandboxConsole.Program+<>c__DisplayClass0_0>(SandboxConsole.Program+<>c__DisplayClass0_0).bar2) 
} 

兩個調用一個表達式。