[英]How can I get rid of double downcasting in this example?
我有以下代碼:
List<object> qIDs = myObject.ExtraData as List<object>; //ExtraData is of type object - Fixed and can't be changed. Old (bad) design.
List<Tuple<string, bool>> itemIds = new List<Tuple<string, bool>>();
foreach (object tuple in qIDs)
{
itemIds.Add((Tuple<string, bool>)tuple);
}
//do something with itemIds
基本上, myObject.ExtraData
是一個存儲元組{string, bool}
列表的object
。 但是,為了檢索List<Tuple<,>>
我必須向下轉換兩次:一次到List<object>
,然后遍歷每個元素並將其添加到List<Tuple<string, bool>>
。 無論如何要擺脫這個?
背景/元數據:需要List<object>
是光榮的黑客行為的一部分,並且當前是List包含兩種不同類型的對象的唯一方法-元組列表和其他結構的列表,以防止代碼消耗列表以更改列表中每種對象的類型。
IEnumerable.OfType可用於僅返回指定Type
對象。
using System.Linq;
var extra = (IEnumerable) myObject.ExtraData;
var itemIds = extra.OfType<Tuple<string, bool>>();
//do something with itemIds
上面的代碼還有一個好處,就是不會浪費內存與列表的另一個副本。
如果您不能按照其他答案中的建議使用OfType
, foreach
可以為您進行第二次轉換:
foreach (Tuple<string, bool> tuple in myObject.ExtraData as List<object>)
{
itemIds.Add(tuple);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.