據我所知,使用as
運算符來投射一個對象,通過一個明確的轉換,通常是更可取的,因爲如果轉換失敗,引用變量將變爲null而不是拋出異常。使用as運算符進行投射,甚至在使用後是運算符來驗證C#中的類類型嗎?
但是,可以說,我檢查一下類的對象是類型,這是一個列表內,使用as
運營商,像這樣之前,
DrawableGameComponent drawComponent;
foreach (component in Components)
{
if (component is DrawableGameComponent)
{
drawComponent = component as DrawableGameComponent;
// do something with drawComponent
}
}
不使用as
運營商失去了它的好處通過首先檢查is
運營商?所以做下面的演員同樣好,因爲我們在嘗試演員之前首先使用is
檢查班級類型?
if (component is DrawableGameComponent)
{
((DrawableGameComponent)componet).Visible = true;
}
我只是想知道是否有某種潛在的一塊,我很想念,或者如果這真的歸結爲口味的問題要使用的模式。後一種模式是否通過顯式轉換創建垃圾?
在此先感謝!
現在仍在繼續鑄造(加上一堆分配)。所以一個很好的LINQ答案 - 但不是一個表現勝利。 –