0

i'm trying to create an Action with reflection. The action I have is something like this.

Action<T, String> someAction(T a, String b) { ... };

I created a method in my class to create the instance of the GenericMethodInfo too be used then in "CreateDelegate". The method is :

public void testMethod<T>(T a, String b) { ... };

And then i try to create my action with reflection

var genericMethod = this.GetType().GetMethod("testMethod").MakeGenericMethod(new Type[] { Type.GetType(myVariableType) };
var actionInstance = Delegate.CreateDelegate(typeof(Action<,>), this, genericMethod);

The problem is that when the last statement is executed (createDelegate) I receive this exception

An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll

Additional information: Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.

Does anyone know how to manage this situation ? Thanks a lot

o0mardok0o
  • 21
  • 4
  • Did you try to use the closed generic type in the `CreateDelegate` call instead of the open one? – thehennyy Apr 12 '17 at 08:40
  • Hi, could you please try to explain me better ? – o0mardok0o Apr 12 '17 at 08:42
  • `Action<,>` is an open or unbound generic type because its type arguments are not specified. You can read more about it [here](http://stackoverflow.com/questions/2173107/what-exactly-is-an-open-generic-type-in-net). – thehennyy Apr 12 '17 at 08:45
  • Ok, thank you. Yes I tried with CreateDelegate(typeof(Action), this, genericMethod) before but it does not work – o0mardok0o Apr 12 '17 at 08:49
  • You have to construct the right delegate type that matches you function definition. So thats probably something like this `typeof(Action<,>).MakeGenericType( new[] { Type.GetType(myVariableType), typeof(string) } );` – thehennyy Apr 12 '17 at 08:55

0 Answers0