简体   繁体   中英

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

I have a collection ot types:

List<Type> types;

And I want to find out which of these types inherit from a concrete generic class without caring about T:

public class Generic<T>

I've tried with:

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

But always returns false, probably due to generic element. Any ideas?

Thanks in advance.

AFAIK, no types report as inheriting from an open generic type: I suspect you'll have to loop manually:

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

Then the sub-list is:

var sublist = types.FindAll(IsGeneric);

or:

var sublist = types.Where(IsGeneric).ToList();

or:

foreach(var type in types) {
    if(IsGeneric(type)) {
       // ...
    }
}

您应该获得列表中特定类型的第一个通用祖先,然后将泛型类型定义与Generic<>进行比较:

genericType.GetGenericTypeDefinition() == typeof(Generic<>)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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