jeudi 4 novembre 2021

c# Call delegate with generic runtime types

I have a delegate that I have created in runtime because I don't know its parameter types in design time. The code is the following:

var delegMethodType = typeof(Func<,,,>).MakeGenericType(type1, type2, type3, returnType);

As you can see I'm using Func<,,,> to represent Func<T1, T2, T3, TReturn>. It works perfectly.

After that, I create my delegate in this way:

var deleg = Delegate.CreateDelegate(delegMethodType, obj, methodInfo);

Where "delegMethodType" is the type for the delegate that I created before, "obj" is the object that receives the call, and "methodInfo" is the reflection method for "obj". This works perfectly.

Now, I need to call the delegate but due to "Delegate.CreateDelegate" returns a basic delegate, I cannot call it with the parameters:

// due to this delegate was created in runtime VS.NET doesn't recognize
// that the delegate allows three parameters and returns a value
var result = deleg(val1, val2, val3);

I can use the delegate with "deleg.DynamicInvoke" but it's slow than calling the delegate with its parameters.

How I can call this delegate with three parameters and get its return value?





Aucun commentaire:

Enregistrer un commentaire