Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create an Action delegate from MethodInfo?

I want to get an action delegate from a MethodInfo object. Is this possible?

like image 803
mokaymakci Avatar asked Jun 11 '10 09:06

mokaymakci


People also ask

How do you call an Action delegate in C#?

C# - Action Delegate Action is a delegate type defined in the System namespace. An Action type delegate is the same as Func delegate except that the Action delegate doesn't return a value. In other words, an Action delegate can be used with a method that has a void return type.

How do you use an Action delegate?

You can use the Action<T> delegate to pass a method as a parameter without explicitly declaring a custom delegate. The encapsulated method must correspond to the method signature that is defined by this delegate.

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.


1 Answers

Use Delegate.CreateDelegate:

// Static method Action action = (Action) Delegate.CreateDelegate(typeof(Action), method);  // Instance method (on "target") Action action = (Action) Delegate.CreateDelegate(typeof(Action), target, method); 

For an Action<T> etc, just specify the appropriate delegate type everywhere.

In .NET Core, Delegate.CreateDelegate doesn't exist, but MethodInfo.CreateDelegate does:

// Static method Action action = (Action) method.CreateDelegate(typeof(Action));  // Instance method (on "target") Action action = (Action) method.CreateDelegate(typeof(Action), target); 
like image 170
Jon Skeet Avatar answered Oct 10 '22 01:10

Jon Skeet