Matrix Bai Matrix Bai - 4 months ago 31
C# Question

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

Answer

The type that you need to pass to MakeGenericMethod is string, not List<string>, because the parameter is used as T.

var mi = typeof(Extensions).GetMethod("List");
var stringGeneric = mi.MakeGenericMethod(typeof(string));
stringGeneric.Invoke(null, new object[] {new List<string> { "list of string"} });

Otherwise, you are making a method that accepts a list of lists of strings.

Comments