2010-03-10 77 views
12

創建泛型委託我有以下代碼:使用反射

class Program 
{ 
    static void Main(string[] args) 
    { 
     new Program().Run(); 
    } 

    public void Run() 
    { 
     // works 
     Func<IEnumerable<int>> static_delegate = new Func<IEnumerable<int>>(SomeMethod<String>); 

     MethodInfo mi = this.GetType().GetMethod("SomeMethod").MakeGenericMethod(new Type[] { typeof(String) }); 
     // throws ArgumentException: Error binding to target method 
     Func<IEnumerable<int>> reflection_delgate = (Func<IEnumerable<int>>)Delegate.CreateDelegate(typeof(Func<IEnumerable<int>>), mi); 

    } 

    public IEnumerable<int> SomeMethod<T>() 
    { 
     return new int[0]; 
    } 
} 

爲什麼我不能創建委託給我的泛型方法?我知道我可以使用mi.Invoke(this, null),但由於我想要執行SomeMethod可能數百萬次,我希望能夠創建委託並將其緩存爲小型優化。

回答

8

你的方法是不是一個靜態方法,所以你需要使用:

Func<IEnumerable<int>> reflection_delgate = (Func<IEnumerable<int>>)Delegate.CreateDelegate(typeof(Func<IEnumerable<int>>), this, mi); 

傳遞「這個」的第二個參數將允許該方法被綁定到當前對象的實例方法。 ..

+0

Doh!非常感謝 - 不知道我是如何錯過的。 – Dathan 2010-03-10 19:28:03