[英]Clean way of dealing with collections of different implementations of Abstract classes?
我有一些Abstract類,這些類具有我項目中某些UserControls
的核心功能。 我也有兩個單獨的實現,都來自Abstract類。 我們稱它們為AbstractImpl1
和AbstractImpl2.
此外,我在多個地方都有抽象UserControls
Collections
。
我遇到的問題是InvalidCastExceptions
我需要遍歷實現,而不是抽象的UserControls才能訪問某些屬性(可視化)。 除了進行try/catch
之外,還有其他解決方法嗎?
例:
在我的項目中,我有Abstract類: AbsUserControl
然后有兩個單獨的實現: AbstractImpl1
和AbstractImpl2
在我的主要形式中,我具有ObservableCollection<AbsUserControl> absControlCollection
,然后迭代我所做的項foreach(AbstractImpl1 userControl in absControlCollection)
以能夠訪問視覺方面。 問題是ObservableCollection<AbsUserControl> absControlCollection
可能由AbstractImpl1
或AbstractImpl2
對象組成。
有沒有解決此問題的干凈方法? 現在,我遍歷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.