使用反射创建通用委托

Dat*_*han 12 .net c# generics reflection delegates

我有以下代码:

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];
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么我不能为我的泛型方法创建委托?我知道我可以使用mi.Invoke(this, null),但由于我想要执行SomeMethod数百万次,我希望能够创建一个委托并将其缓存为一个小优化.

Ree*_*sey 8

您的方法不是静态方法,因此您需要使用:

Func<IEnumerable<int>> reflection_delgate = (Func<IEnumerable<int>>)Delegate.CreateDelegate(typeof(Func<IEnumerable<int>>), this, mi);
Run Code Online (Sandbox Code Playgroud)

将"this"传递给第二个参数将允许该方法绑定到当前对象上的实例方法...