using System; using System.Reflection; namespace RFTest { //類ReflectionTest中定義了一個泛型函數DisplayType和泛型類MyGenericClass class ReflectionTest { //泛型類MyGenericClass有個靜態函數DisplayNestedType public class MyGenericClass<T> { public static void DisplayNestedType() { Console.WriteLine(typeof(T).ToString()); } } public void DisplayType<T>() { Console.WriteLine(typeof(T).ToString()); } } class Program { static void Main(string[] args) { ReflectionTest rt = new ReflectionTest(); MethodInfo mi = rt.GetType().GetMethod("DisplayType");//先獲取到DisplayType<T>的MethodInfo反射對象 mi.MakeGenericMethod(new Type[] { typeof(string) }).Invoke(rt, null);//然后使用MethodInfo反射對象調用ReflectionTest類的DisplayType<T>方法,這時要使用MethodInfo的MakeGenericMethod函數指定函數DisplayType<T>的泛型類型T Type myGenericClassType = rt.GetType().GetNestedType("MyGenericClass`1");//這里獲取MyGenericClass<T>的Type對象,注意GetNestedType方法的參數要用MyGenericClass`1這種格式才能獲得MyGenericClass<T>的Type對象 myGenericClassType.MakeGenericType(new Type[] { typeof(float) }).GetMethod("DisplayNestedType", BindingFlags.Static | BindingFlags.Public).Invoke(null, null); //然后用Type對象的MakeGenericType函數為泛型類MyGenericClass<T>指定泛型T的類型,比如上面我們就用MakeGenericType函數將MyGenericClass<T>指定為了MyGenericClass<float>,然后繼續用反射調用MyGenericClass<T>的DisplayNestedType靜態方法 Console.ReadLine(); } } }