using System;
using System.Reflection;
using static Reflect.Demo.ReflectionTest;
namespace Reflect.Demo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World! reflect");
ReflectionTest rt = new ReflectionTest();
//先获取到DisplayType<T>的MethodInfo反射对象
MethodInfo mi = rt.GetType().GetMethod("DisplayType");
//然后使用MethodInfo反射对象调用ReflectionTest类的DisplayType<T>方法,
//这时要使用MethodInfo的MakeGenericMethod函数指定函数DisplayType<T>的泛型类型T
mi.MakeGenericMethod(new Type[] { typeof(string) }).Invoke(rt, null);
//这里获取MyGenericClass<T>的Type对象,注意GetNestedType方法的参数要用MyGenericClass`1这种格式才能获得MyGenericClass<T>的Type对象
Type myGenericClassType = rt.GetType().GetNestedType("MyGenericClass`1");
//然后用Type对象的MakeGenericType函数为泛型类MyGenericClass<T>指定泛型T的类型,
//比如上面我们就用MakeGenericType函数将MyGenericClass<T>指定为了MyGenericClass<float>,然后继续用反射调用MyGenericClass<T>的DisplayNestedType静态方法
myGenericClassType.MakeGenericType(new Type[] { typeof(float) }).GetMethod("DisplayNestedType", BindingFlags.Static | BindingFlags.Public).Invoke(null, null);
Type myGenericClassType2 = typeof(MyGenericClass<>);
myGenericClassType2.MakeGenericType(typeof(double)).GetMethod("DisplayNestedType").Invoke(null, null);
Type myGenericClassType3 = typeof(MyGenericClass<>);
//非静态方法,需要先创建实例调用
//myGenericClassType2.MakeGenericType(typeof(double)).GetMethod("DisplayType").Invoke(null, null);
Type geneTp = myGenericClassType3.MakeGenericType(typeof(int));
MyGenericClass<int> obj = Activator.CreateInstance(geneTp) as MyGenericClass<int>;
obj.DisplayType();
object obj2 = Activator.CreateInstance(geneTp);
MethodInfo mi2 = obj2.GetType().GetMethod("DisplayType");
mi2.Invoke(obj2, null);
Console.ReadKey();
}
}
class ReflectionTest
{
public class MyGenericClass<T>
{
public static void DisplayNestedType()
{
Console.WriteLine(typeof(T).ToString());
}
public void DisplayType()
{
Console.WriteLine(typeof(T).ToString());
}
}
public void DisplayType<T>()
{
Console.WriteLine(typeof(T).ToString());
}
}
}
结果:

网友评论