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

Ign*_*cia 4 .net c# generics reflection

我有一个集合ot类型:

List<Type> types;
Run Code Online (Sandbox Code Playgroud)

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

public class Generic<T>
Run Code Online (Sandbox Code Playgroud)

我尝试过:

foreach(Type type in types)
{
    if (typeof(Generic<>).IsAssignableFrom(type))
    {
        ....
    }
}
Run Code Online (Sandbox Code Playgroud)

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

提前致谢.

Mar*_*ell 6

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

static bool IsGeneric(Type type)
{
    while (type != null)
    {
        if (type.IsGenericType
            && type.GetGenericTypeDefinition() == typeof(Generic<>))
        {
            return true;
        }
        type = type.BaseType;
    }
    return false;
} 
Run Code Online (Sandbox Code Playgroud)

然后子列表是:

var sublist = types.FindAll(IsGeneric);
Run Code Online (Sandbox Code Playgroud)

要么:

var sublist = types.Where(IsGeneric).ToList();
Run Code Online (Sandbox Code Playgroud)

要么:

foreach(var type in types) {
    if(IsGeneric(type)) {
       // ...
    }
}
Run Code Online (Sandbox Code Playgroud)