2016-08-05 61 views
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 ""; 
    } 
} 

使用反射來調用這兩個擴展方法如何使用C#反射調用具有通用List參數的擴展方法?

//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

回答

1

,你需要傳遞給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"} }); 

否則,您正在接受一個字符串列表的列表的方法。

0

因爲typeof(列表<「T」>)沒有返回正確的類型。

您應該編寫一個擴展方法來獲取泛型列表的類型。

,或者你可以修改這樣

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 }); 

代碼=>它的工作原理

相關問題