如何获取从泛型类继承的集合的所有类型
本文关键字:继承 集合 类型 泛型类 何获取 获取 | 更新日期: 2024-06-14 06:51:24
我有一个类型集合:
List<Type> types;
我想找出这些类型中的哪一个继承自具体的泛型类,而不关心T:
public class Generic<T>
我尝试过:
foreach(Type type in types)
{
if (typeof(Generic<>).IsAssignableFrom(type))
{
....
}
}
但总是返回false,可能是由于泛型元素。有什么想法吗?
提前谢谢。
AFAIK,没有类型报告为继承自open泛型类型:我怀疑您必须手动循环:
static bool IsGeneric(Type type)
{
while (type != null)
{
if (type.IsGenericType
&& type.GetGenericTypeDefinition() == typeof(Generic<>))
{
return true;
}
type = type.BaseType;
}
return false;
}
则子列表为:
var sublist = types.FindAll(IsGeneric);
或:
var sublist = types.Where(IsGeneric).ToList();
或:
foreach(var type in types) {
if(IsGeneric(type)) {
// ...
}
}
您应该获得列表中特定类型的第一个泛型祖先,然后将泛型类型定义与Generic<>
:进行比较
genericType.GetGenericTypeDefinition() == typeof(Generic<>)