I try create delegate type using an Expression class, but when I try create delegate from instance of MethodInfo I've got an ArgumentException. I using .NET 4.0 Here code:
var method = /*...*/;
List<Type> tArgs = new List<Type> { method.ReturnType };
var mparams = method.GetParameters();
mparams.ToList().ForEach(p => tArgs.Add(p.ParameterType));
var delDecltype = Expression.GetDelegateType(tArgs.ToArray());
return Delegate.CreateDelegate(delDecltype, method);
P.S. Sorry for my bad english;)
Once a delegate type is declared, a delegate object must be created with the new keyword and be associated with a particular method. When creating a delegate, the argument passed to the new expression is written similar to a method call, but without the arguments to the method.
For example, a delegate with a parameter of type Hashtable and a return type of Object can represent a method with a parameter of type Object and a return value of type Hashtable. Creates a delegate of the specified type that represents the specified instance method to invoke on the specified class instance. The Type of delegate to create.
Finally, delegates are created for static method M4 of type C and type F; each method has the declaring type as its first argument, and an instance of the type is supplied, so the delegates are closed over their first arguments. Method M4 of type C displays the ID properties of the bound instance and of the argument.
Whenever a new set of argument types or return value type is needed, a new delegate type must be declared. Instantiating a delegate. After a delegate type has been declared, a delegate object must be created and associated with a particular method.
If you read the documentation for Expression.GetDelegateType()
, you would see that the return type has to be the last argument.
That means this code should work:
var tArgs = new List<Type>();
foreach (var param in method.GetParameters())
tArgs.Add(param.ParameterType);
tArgs.Add(method.ReturnType);
var delDecltype = Expression.GetDelegateType(tArgs.ToArray());
return Delegate.CreateDelegate(delDecltype, method);
This code works for static methods only though. If you want create a delegate from instance method, you need to provide the instance you want to call the method on. To do that, change the last line to:
return Delegate.CreateDelegate(delDecltype, instance, method);
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