views:

210

answers:

1

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 optimization.

+6  A: 

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...

Reed Copsey
Doh! Thanks a bunch - don't know how I missed that.
Dathan