2015-07-20 59 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而不是引发异常