2016-07-01 75 views
2

我試圖理解委託,所以我只寫了一個小的嘗試項目; 我有類d:C#反思委託異常:必須派生自委託

class D 
{ 
    private static void Func1(Object o) 
    { 
     if (!(o is string)) return; 
     string s = o as string; 
     Console.WriteLine("Func1 going to sleep"); 
     Thread.Sleep(1500); 
     Console.WriteLine("Func1: " + s); 
    } 
} 

,並在主要的即時通訊使用:

MethodInfo inf = typeof(D).GetMethod("Func1", BindingFlags.NonPublic | BindingFlags.Static); 
Delegate d = Delegate.CreateDelegate(typeof(D), inf); 

的方法信息獲取正確的信息,但createDelegate方法方法拋出一個異常,saybg該類型必須從委託派生。

我該如何解決這個問題?

+0

嗯是的......您只能調用'CreateDelegate'來創建委託實例。你期望該代碼做什麼? –

回答

5

如果您想爲Func1方法創建委託,您需要指定要創建的委託的類型。在這種情況下,你可以使用Action<object>

MethodInfo inf = typeof(D).GetMethod("Func1", BindingFlags.NonPublic | BindingFlags.Static); 
Delegate d = Delegate.CreateDelegate(typeof(Action<object>), inf); 
+0

謝謝!它正在工作 – Erez

0

傳遞給CreateDelegate方法的類型實際上不是,你將使用調用方法函數的類,但類型的類型。因此,它將是與原始方法具有相同參數的委託類型:

public delegate void MyDelegate(Object o); 
... 
MethodInfo inf = typeof(D).GetMethod("Func1", BindingFlags.NonPublic | BindingFlags.Static); 
Delegate d = Delegate.CreateDelegate(typeof(MyDelegate), inf);