Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create delegate type in runtime

Tags:

c#

.net

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

like image 735
Alex Sabaka Avatar asked Aug 12 '11 23:08

Alex Sabaka


People also ask

How do you create a delegate in a method?

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.

What is an example of a delegate in Java?

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.

How are delegates created for static methods in Java?

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.

When do you need to declare a delegate type?

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.


1 Answers

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);
like image 55
svick Avatar answered Oct 14 '22 05:10

svick