vendredi 8 décembre 2017

Delegate with generic type only known at runtime

In my code I have declared an interface as follows:

interface IGeneric
{
    T GetOfType<T>();
}

And I want to invoke the interface's method with a generic type only known at runtime. This is how I do it currently, and it works:

Type genericArgument = ...
object interfaceImplementation = ...

MethodInfo methodInfo = typeof(IGeneric).GetMethod("GetOfType").MakeGenericMethod(genericArgument);
methodInfo.Invoke(interfaceImplementation, null);

but because I have to call this part of code quite often, I would like to cache the method info in a delegate. I tried this delegate definition

private delegate T GetOfTypeDelegate<T>();

and tried to create a delegate using the method info I retrieved like shown above like this:

GetOfTypeDelegate<?> deleg = (GetOfTypeDelegate<?>) Delegate.CreateDelegate(typeof(GetOfTypeDelegate<?>), methodInfo);

but since I don't know the type of the generic argument at compile time, I don't know what to put where I used the ? or how to make this work at all.

Any help is gladly appreciated.





Aucun commentaire:

Enregistrer un commentaire