c#反射-构建泛型和数组

演示类

在反射中,反射获取的类型可以是么有填入类型参数的类型。
其中和类型参数有关的成员无法获取和执行。

以下是示例类

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>[,,,]));
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值