簡體   English   中英

處理抽象類不同實現的集合的干凈方法?

[英]Clean way of dealing with collections of different implementations of Abstract classes?

我有一些Abstract類,這些類具有我項目中某些UserControls的核心功能。 我也有兩個單獨的實現,都來自Abstract類。 我們稱它們為AbstractImpl1AbstractImpl2. 此外,我在多個地方都有抽象UserControls Collections

我遇到的問題是InvalidCastExceptions我需要遍歷實現,而不是抽象的UserControls才能訪問某些屬性(可視化)。 除了進行try/catch之外,還有其他解決方法嗎?

例:

在我的項目中,我有Abstract類: AbsUserControl然后有兩個單獨的實現: AbstractImpl1AbstractImpl2

在我的主要形式中,我具有ObservableCollection<AbsUserControl> absControlCollection ,然后迭代我所做的項foreach(AbstractImpl1 userControl in absControlCollection)以能夠訪問視覺方面。 問題是ObservableCollection<AbsUserControl> absControlCollection可能由AbstractImpl1AbstractImpl2對象組成。

有沒有解決此問題的干凈方法? 現在,我遍歷absControlCollection對象的每個地方都用try/catch塊將其包圍,嘗試遍歷AbstractImpl1對象,然后捕獲InvalidCastException並繼續遍歷AbstractImpl2對象。

讓我知道是否需要更多信息。 謝謝!

使用OfType為您進行過濾:

foreach(AbstractImpl1 userControl in
    absControlCollection.OfType<AbstractImpl1>())
{
    ...
}

OfType的替代方法; 投放無例外:

foreach(AbsUserControl control in absControlCollection)
{
    if(control is AbstractImpl1)
    {
        AbstractImpl1 i1 = (AbstractImpl1)control;
        DoStuff(i1);
    }
    if(control is AbstractImpl2)
    {
        AbstractImpl2 i2 = (AbstractImpl2)control;
        DoOtherStuff(i2);
    }
}

您可以使用LINQ的OfType方法來安全地僅過濾出您感興趣的具體實現。然后,您的foreach如下所示:

foreach(var userControl in abcControlCollection.OfType<AbstractImpl1>())
{
    /* ... */
}

暫無
暫無

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

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