簡體   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