2015-07-20 64 views
0

假設我有返回類對象A類型轉換在C#對象

A getItem(int index)

現在我的代碼下面的行中,一種方法(I假設BA子類)

B b = (B) obj.getItem(i);

但在此之前,我必須確保我可以將它轉換爲B,因爲getItem可以返回某個其他子類的對象,比如說CA

像這樣的事情

if(I can typecast obj.getItem(i) to B) { 
      B b = (B) obj.getItem(i); 
    } 

我如何能做到這一點的,?

+0

這裏是一個有用的鏈接::) http://stackoverflow.com/questions/7042314/can-i-check-if-a-variable-can-be-cast-到一個指定的型 – NicoRiff

回答

2
var item = obj.GetItem(i); 
if(item is B) { 
    B b = (B) item; 
} 
5

兩個選項:

object item = obj.getItem(i); // TODO: Fix method naming... 
// Note: redundancy of check/cast 
if (item is B) 
{ 
    B b = (B) item; 
    // Use b 
} 

或者:

object item = obj.getItem(i); // TODO: Fix method naming... 
B b = item as B; 
if (item != null) 
{ 
    // Use b 
} 

兩者之間更詳細的比較見"Casting vs using the 'as' keyword in the CLR"

1

使用as代替:

B b = obj.getItem(i) as B; 
if(b != null) 
    // cast worked 

as運算符是像一個轉換操作。但是,如果轉換不可能,as返回null而不是引發異常