samedi 1 octobre 2016

Invoke a generic method with a subtype of the generic parameter type

I am trying to invoke a generic method via reflection using a subtype of the generic parameter type. Here's the situation :

public abstract class MyClass<T> where T : class
{
}

public static class Caller
{
    public static void Do<T>(MyClass<T> param1, string param2 = null)
    {

    }
}

public class ConcreteClass : MyClass<string>
{

}

However when I try to do :

ConcreteClass instance = Activator.CreateInstance(typeof(ConcreteClass));
MethodInfo methodInfo = typeof(Caller).GetMethod("Do");
methodInfo = methodInfo.MakeGenericMethod(typeof(ConcreteClass));
methodInfo.Invoke(null, new object[] { instance, Type.Missing });

I am getting an exception essentially saying :

Cannot convert type 'ConcreteClass' to type 'MyClass'

The exception message is very clear, however I don't seem to find how I can achieve what I am after.





Aucun commentaire:

Enregistrer un commentaire