jeudi 4 août 2016

How to use C# reflection to invoke an extension method with generic List parameter?

static class Extensions
{
    public static string Primary<T>(this T obj)
    {
        Debug.Log(obj.ToString());
        return "";
    }

    public static string List<T>(this List<T> obj)
    {
        Debug.Log(obj.ToString());
        return "";
    }
}

Use reflection to invoke the two extension methods

//This works
var pmi = typeof(Extensions).GetMethod("Primary");
var pgenerci = pmi.MakeGenericMethod(typeof(string));
pgenerci.Invoke(null, new object[] {"string"  });

//This throw a "ArgumentException: failed to convert parameters"
var mi = typeof(Extensions).GetMethod("List");
var stringGeneric = mi.MakeGenericMethod(typeof(List<string>));
stringGeneric.Invoke(null, new object[] {new List<string> { "list of string"}, });

I'm working with Unity3d, so the .net version is 3.5





Aucun commentaire:

Enregistrer un commentaire