Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何获取从泛型类继承的集合的所有类型?_C#_.net_Generics_Reflection - Fatal编程技术网

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

C# 如何获取从泛型类继承的集合的所有类型?,c#,.net,generics,reflection,C#,.net,Generics,Reflection,我收集了一系列类型: List<Type> types; 列表类型; 我想找出哪些类型继承自具体的泛型类,而不关心T: public class Generic<T> 公共类泛型 我试过: foreach(Type type in types) { if (typeof(Generic<>).IsAssignableFrom(type)) { .... } } foreach(类型中的类型) { if(type

我收集了一系列类型:

List<Type> types;
列表类型;
我想找出哪些类型继承自具体的泛型类,而不关心T:

public class Generic<T>
公共类泛型
我试过:

foreach(Type type in types)
{
    if (typeof(Generic<>).IsAssignableFrom(type))
    {
        ....
    }
}
foreach(类型中的类型)
{
if(typeof(Generic).IsAssignableFrom(type))
{
....
}
}
但总是返回false,可能是由于泛型元素。有什么想法吗


提前感谢。

您应该为列表中的特定类型获取第一个泛型祖先,然后将泛型类型定义与
泛型比较:

genericType.GetGenericTypeDefinition()==typeof(Generic)

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

static bool IsGeneric(Type type)
{
    while (type != null)
    {
        if (type.IsGenericType
            && type.GetGenericTypeDefinition() == typeof(Generic<>))
        {
            return true;
        }
        type = type.BaseType;
    }
    return false;
} 
或:

或:


是的,否决票很奇怪,你能不能先迭代
类型
列表,然后添加
elem.GetType().IsGenericType
?@AndreiV:我想要的只是泛型类的继承人,而不是任何泛型类。对不起,我没有完全理解。我想现在还为时过早…@MarcGravel:是的,“获得第一个通用祖先”假设了这一点。否则,我无法想象,这个事实怎么能成立;当然,第一个通用祖先不一定是你想要的;p它可以是
类Foo:Bar
类Bar:Generic
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)) {
       // ...
    }
}