开发者

Create generic delegate using reflection

开发者 https://www.devze.com 2022-12-22 08:02 出处:网络
I have the following code: class Program { static void Main(string[] args) { new Program().Run(); } public void Run()

I have the following code:

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];
    }
}

Why can't I create a delegate to my generic method? I know I could just use mi.Invoke(this, null), but since I'm going to want to execute SomeMethod potentially several million times, I'd like to be able to create a delegate and cache it as a small optimiz开发者_开发技巧ation.


You method isn't a static method, so you need to use:

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

Passing "this" to the second argument will allow the method to be bound to the instance method on the current object...

0

精彩评论

暂无评论...
验证码 换一张
取 消