反射獲取泛型類、泛型方法
1 using System; 2 using System.Reflection; 3 4 namespace RFTest 5 { 6 //類ReflectionTest中定義了一個泛型函數DisplayType和泛型類MyGenericClass 7 class ReflectionTest 8 { 9 //泛型類MyGenericClass有個靜態函數DisplayNestedType 10 public class MyGenericClass<T> 11 { 12 public static void DisplayNestedType() 13 { 14 Console.WriteLine(typeof(T).ToString()); 15 } 16 } 17 18 public void DisplayType<T>() 19 { 20 Console.WriteLine(typeof(T).ToString()); 21 } 22 } 23 24 class Program 25 { 26 static void Main(string[] args) 27 { 28 ReflectionTest rt = new ReflectionTest(); 29 30 MethodInfo mi = rt.GetType().GetMethod("DisplayType");//先獲取到DisplayType<T>的MethodInfo反射對象 31 mi.MakeGenericMethod(new Type[] { typeof(string) }).Invoke(rt, null);//然后使用MethodInfo反射對象調用ReflectionTest類的DisplayType<T>方法,這時要使用MethodInfo的MakeGenericMethod函數指定函數DisplayType<T>的泛型類型T 32 33 Type myGenericClassType = rt.GetType().GetNestedType("MyGenericClass`1");//這里獲取MyGenericClass<T>的Type對象,注意GetNestedType方法的參數要用MyGenericClass`1這種格式才能獲得MyGenericClass<T>的Type對象 34 myGenericClassType.MakeGenericType(new Type[] { typeof(float) }).GetMethod("DisplayNestedType", BindingFlags.Static | BindingFlags.Public).Invoke(null, null); 35 //然后用Type對象的MakeGenericType函數為泛型類MyGenericClass<T>指定泛型T的類型,比如上面我們就用MakeGenericType函數將MyGenericClass<T>指定為了MyGenericClass<float>,然后繼續用反射調用MyGenericClass<T>的DisplayNestedType靜態方法 36 37 Console.ReadLine(); 38 } 39 } 40 }