I want to get an action delegate from a MethodInfo object. Is this possible?
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With