1
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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.