2010-03-10 110 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