Matrix Bai
Matrix Bai

Reputation: 1107

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

Upvotes: 1

Views: 3097

Answers (2)

Alex Nguyen
Alex Nguyen

Reputation: 1080

Because typeof(List<"T">) did not return the right type.

You should write an extension method to get the type of generic list.

or you can modify your code like this

var listItem = new List<string> { "alex", "aa" };
var typeOfGeneric = listItem.GetType().GetGenericArguments().First<Type>();
var mi = typeof(Extensions).GetMethod("List");
var stringGeneric = mi.MakeGenericMethod(typeOfGeneric);
stringGeneric.Invoke(null, new object[] { listItem });

=> it works

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

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.

Upvotes: 1

Related Questions