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 "";
}
}
使用反射来调用两个扩展方法
//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"}, });
我正在使用Unity3d,因此.net版本是3.5
你需要传递的类型MakeGenericMethod
是string
,不是List<string>
,因为参数作为T
。
var mi = typeof(Extensions).GetMethod("List");
var stringGeneric = mi.MakeGenericMethod(typeof(string));
stringGeneric.Invoke(null, new object[] {new List<string> { "list of string"} });
否则,您正在制作一个接受字符串列表列表的方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句