簡體   English   中英

如何檢查基本類型列表是否至少包含某些子類型的一個實例

[英]How to check if a list of base type contains at least one instance of some child types

我有一個這樣的基類列表:

List<BaseClass> ChildClasses

我有這樣的子班:

class ChildFoo : BaseClass {}
class ChildBar : BaseClass {}
class ChildBaz : BaseClass {}
class ChildQax : BaseClass {}
class ChildBox : BaseClass {}
...

我需要實現一種方法,該方法可以查詢ChildClasses列表,以查看它是否具有我傳遞給它的所有類型,這些類型都是從BaseClass派生的。

因此,如果我為ChildFooChildBar類型調用此方法,則在ChildClasses列表包含至少一個ChildFooChildBar實例的情況下,它應該返回true。

我該如何處理這種情況?

如果ChildClasses列表包含至少一個ChildFoo和ChildBar實例,則應返回true。

您可以將OfTypeAny一起使用。 然后,您可以多次組合表達式。

var containsFooAndBar = ChildClasses.OfType<ChildFoo>().Any() 
                     && ChildClasses.OfType<ChildBar>().Any();

備用

您也可以從另一個方向進行處理。 創建需要包括的所有必需類型的列表,然后使用ChildClasses列表作為輸入對該列表執行查詢。 這只是上面編寫的一種不同方式, ChildClasses集合仍在2x上迭代。

Type[] mandatoryTypes = new Type[] {typeof(ChildFoo), typeof(ChildBar)};
var containsFooAndBar = mandatoryTypes.All(mandatoryType => ChildClasses.Any(instance => instance != null && mandatoryType == instance.GetType()));

假設繼承層次結構沒有比您的示例更深入...

創建列表中實際類型的哈希集:

var actualTypes= new HashSet<Type>(ChildClasses.Select(x=>x.GetType()));

然后創建所需類型的哈希集:

var requiredTypes = new HashSet<Type>
        {
            typeof(ChildFoo),
            typeof(ChildBar)
        };

從一組必需的類型中刪除所有實際的類型:

requiredTypes.ExceptWith(actualTypes);

如果requiredTypes.Count == 0則列表包含所有必需的類型。 如果requiredTypes.Count > 0 ,則缺少類型,這些類型將保留為requiredTypes的內容。

如果所需類型的數量是可變的(讓調用者直接在哈希集中傳遞或從中構造哈希集的IEnumerable中傳遞)並且對於ChildClasses或所需類型中的大量項目都具有出色的性能,則此方法應該更易於實現。

您可以創建一個方法,該方法獲取您的類列表以及類型數組,然后檢查提供的列表是否包含所有這些類型:

    static bool ContainsTypes(List<BaseClass> list, params Type[] types)
    {
        return types.All(type => list.Any(x => x != null && type == x.GetType()));
    }

並像這樣實現它:

    List<BaseClass> baseClasses = new List<BaseClass>();
    baseClasses.Add(new ChildFoo());
    baseClasses.Add(new ChildBar());
    //Population code here...
    var result = ContainsTypes(baseClasses, typeof(ChildFoo), typeof(ChildBar));

或者如果您想使用擴展方法

public static class Extensions
{
    public static bool ContainsTypes(this List<BaseClass> list, params Type[] types)
    {
        return types.All(type => list.Any(x => x != null && type == x.GetType()));
    }
}

再次實現如下:

List<BaseClass> baseClasses = new List<BaseClass>();
baseClasses.Add(new ChildFoo());
baseClasses.Add(new ChildBar());
//Population code here...
var result = baseClasses.ContainsTypes(typeof(ChildFoo), typeof(ChildBar));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM