演示类
在反射中,反射获取的类型可以是么有填入类型参数的类型。
其中和类型参数有关的成员无法获取和执行。
以下是示例类
class TestClass<T>
{
public int Id;
public T Value;
public void SomeThing<B>(B b)
{
Console.WriteLine(typeof(B).Name);
}
public void SomeThing(T b)
{
Console.WriteLine(typeof(T).Name);
}
}
构建泛型类
带有泛型的类型,在typeof获取Type时,中间的泛型参数可以留空。有多个泛型时,使用逗号分隔。
Type typeT = typeof(TestClass<>);
Type type1 = typeT.MakeGenericType(typeof(int));//用指定类型构建泛型
FieldInfo f1 = typeT.GetField("Value");
FieldInfo f2 = type1.GetField("Value");
Console.WriteLine(f1.FieldType);//T
Console.WriteLine(f2.FieldType);//System.Int32
还原泛型类
Type typeInt = typeof(TestClass<int>);
Type type2 = typeInt.GetGenericTypeDefinition();//获取没有填入泛型参数的泛型类
Console.WriteLine(type2 == typeT);//相等
Console.WriteLine(type1 == typeInt);//相等
Type[] types = typeInt.GetGenericArguments();//获取泛型参数列表
泛型类的占位符是一个有效的Type
获取没有泛型参数的Type的方法,需要使用这个Type获取。
Type[] types = typeT.GetGenericArguments();//获取泛型参数列表
MethodInfo m1 = typeT.GetMethod("SomeThing", new Type[] { types[0] });
MethodInfo m2 = typeInt.GetMethod("SomeThing", new Type[] { typeof(int) });
获取泛型方法
不会。目前我只能遍历成员来筛选
var m3 = type1.GetMethods().First(s => s.ContainsGenericParameters);
构建泛型方法
泛型方法的构建和类差不多。使用MakeGenericMethod构建,GetGenericMethodDefinition还原
var m4 = m3.MakeGenericMethod(typeof(int));
var m5 = m4.GetGenericMethodDefinition();
var types2 = m4.GetGenericArguments();
构建数组
使用MakeArrayType方法构建,参数代表多维数组。
Type arrT = type1.MakeArrayType();
Console.WriteLine(arrT == typeof(TestClass<int>[]));
arrT = type1.MakeArrayType(2);
Console.WriteLine(arrT == typeof(TestClass<int>[,]));
arrT = type1.MakeArrayType(4);
Console.WriteLine(arrT == typeof(TestClass<int>[,,,]));