2011-07-21 29 views
3

據我所知,使用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; 
} 

我只是想知道是否有某種潛在的一塊,我很想念,或者如果這真的歸結爲口味的問題要使用的模式。後一種模式是否通過顯式轉換創建垃圾?

在此先感謝!

回答

11

更好(保存一個「演員」 - 比較產生IL):

DrawableGameComponent drawComponent; 
foreach (component in Components) 
{ 
    drawComponent = component as DrawableGameComponent; 
    if (drawComponent != null) 
    { 


     // do something with drawComponent 
    } 
} 
1

我會用

DrawableGameComponent drawComponent; 
foreach (component in Components) 
{ 
    drawComponent = component as DrawableGameComponent; 
    if (drawComponent != null) 
    { 
     // do something with drawComponent 
    } 
} 

FXCop可以幫助拿起你的代碼的地方,可以從很小的優化中受益像這樣

5

你正在使用as操作符來檢查這個類兩次,儘管我懷疑除非在一個真正的大規模循環中開銷會明顯。

我更喜歡使用的和測試空,並清理你的聲明,甚至更少的行:

foreach (component in Components) 
{ 
    var drawComponent = component as DrawableGameComponent; 
    if (drawComponent != null) 
    { 
      // do something with drawComponent 
    } 
} 
0

通過結合isas你有效地做類型檢查兩次。在這種情況下使用as(如其他答案所示)可以獲得您想要的結果,並生成更具可讀性的IMO代碼。

0

你可以使用LINQ來獲得你的類型。這樣不需要鑄造。

public class A 
{ 
} 

public class B : A 
{ 
    public bool Visible { get; set; } 
} 

public class C : A 
{ 
} 

void Main() 
{ 
    var data = new List<A> { new A(), new B(), new C(), new B() }; 

    data.OfType<B>().ToList().ForEach(x => x.Visible = true); 
} 
+1

現在仍在繼續鑄造(加上一堆分配)。所以一個很好的LINQ答案 - 但不是一個表現勝利。 –

相關問題