Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create generic delegate using reflection

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.

like image 696
Dathan Avatar asked Mar 10 '10 19:03

Dathan


People also ask

How do you define generic delegates?

Delegates defined within a generic class can use the generic class type parameters in the same way that class methods do. Generic delegates are especially useful in defining events based on the typical design pattern because the sender argument can be strongly typed and no longer has to be cast to and from Object.

What are the three types of generic delegates in C#?

Func, Action and Predicate are generic inbuilt delegates present in System namespace. All three can be used with method, anonymous method and lambda expression.

What is MethodInfo C#?

The MethodInfo class represents a method of a type. You can use a MethodInfo object to obtain information about the method that the object represents and to invoke the method.

How do I invoke a delegate?

Create the delegate and matching procedures Create a delegate named MySubDelegate . Declare a class that contains a method with the same signature as the delegate. Define a method that creates an instance of the delegate and invokes the method associated with the delegate by calling the built-in Invoke method.


1 Answers

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

like image 136
Reed Copsey Avatar answered Sep 20 '22 15:09

Reed Copsey