繁体   English   中英

如何获取从泛型类继承的所有类型的集合?

[英]How to get all the types of a collection that inherit from a generic class?

我有一个集合ot类型:

List<Type> types;

我想找出哪些类型继承自具体的泛型类而不关心T:

public class Generic<T>

我尝试过:

foreach(Type type in types)
{
    if (typeof(Generic<>).IsAssignableFrom(type))
    {
        ....
    }
}

但总是返回false,可能是由于泛型元素。 有任何想法吗?

提前致谢。

AFAIK,没有类型报告继承自开放泛型类型:我怀疑你必须手动循环:

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<>)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM