如何使用基类比较泛型类型

时间:2015-05-21 16:33:08

标签: c# generics

是否可以使用基类比较泛型类型?例如:

propertyInfo.PropertyType.IsSubclassOf(typeof(List<BaseClass>))

我想我可以做到以下几点,但有更短的方法吗?

Type type = propertyInfo.PropertyType;
type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>) && type.GetGenericArguments()[0].IsSubclassOf(typeof(BaseClass))

1 个答案:

答案 0 :(得分:0)

虽然您的解决方案是一种可能性,但它并不能说明目标是封闭泛型类型的子类,例如NamedList : List<BaseClass>, IKeyedItemCollection<string, BaseClass>,因为{{1} }将返回IsGenericType

相反,当您处理泛型中的差异时,请考虑.IsAssignableFrom method

false

即使对于typeof(IEnumerable<BaseClass>).IsAssignableFrom(PropertyInfo.PropertyType) DerivedList DerivedList : List<DerivedClass>,这也会返回true。但是,由于DerivedClass : BaseClass 方差容差,因此无法检查List的可分配性