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;)
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:
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: