Creating a delegate type at runtime

I am trying to create a delegate type using the Expression class, but when I try to create a delegate from an instance of MethodInfo, I have an ArgumentException. I am using .NET 4.0. Here is the 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); 

PS Sorry for my bad english;)

+6
source share
1 answer

If you read the documentation for Expression.GetDelegateType() , you will see that the return type should be the last argument.

This means that 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 only works for static methods. If you want to create a delegate from an instance method, you need to provide the instance on which you want to call the method. To do this, change the last line to:

 return Delegate.CreateDelegate(delDecltype, instance, method); 
+11
source

Source: https://habr.com/ru/post/894956/


All Articles