[C#.NET 拾遗补漏]04:你必须知道的反射 (3)

由于 List<> 本身也是泛型,所以上面的判断不严谨,我们需要知道的是对象是不是一个构造泛型(List<int>)。而 Type 类还提供了一些有用的属性:

typeof(List<>).IsGenericType // true typeof(List<>).IsGenericTypeDefinition // true typeof(List<>).IsConstructedGenericType// false typeof(List<int>).IsGenericType // true typeof(List<int>).IsGenericTypeDefinition // false typeof(List<int>).IsConstructedGenericType// true

IsConstructedGenericType 和 IsGenericTypeDefinition 分别用来判断某个泛型是不是构造泛型和非构造泛型。

再结合 Type 的 GetGenericArguments() 方法,就可以很容易地知道某个泛型实例是用什么泛型参数构建的了,例如:

static void ShowGenericArguments(object o) { if (o == null) return; Type t = o.GetType(); if (!t.IsConstructedGenericType) return; foreach (Type genericTypeArgument in t.GetGenericArguments()) Console.WriteLine(genericTypeArgument.Name); }

以上是关于反射的干货知识,都是从实际项目开发中总结而来,希望对你的开发有帮助。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpwwpf.html