可能重复:
使用CLR中的'as'关键字进行转换
哪种方法被认为是最佳做法?
先投?
public string Describe(ICola cola)
{
var coke = cola as CocaCola;
if (coke != null)
{
string result;
// some unique coca-cola only code here.
return result;
}
var pepsi = cola as Pepsi;
if (pepsi != null)
{
string result;
// some unique pepsi only code here.
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
或者我应该先检查,然后再投?
public string Describe(ICola cola)
{
if (cola is CocaCola)
{
var coke = (CocaCola) cola;
string result;
// some unique coca-cola only code here.
return result;
}
if (cola is Pepsi)
{
var pepsi = (Pepsi) cola;
string result;
// some unique pepsi only code here.
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
你能看到其他任何方式吗?
EMP*_*EMP 19
如果对象可能是您想要的类型,也可能不是您想要的类型,那么as运算符(您的第一种方法)在两个方面更好:
is关键字时,C#编译器在内部将其转换为as,即coke is Cola相当于(coke as Cola) != null)如果对象应始终是请求的类型,那么只需执行(Coke)cola并让它抛出异常(如果不是这种情况).
第一个(第一个通过as)效率稍高,所以在这方面,它可能是最好的做法.
但是,上面的代码通常会显示一些"代码味道".如果可能的话,我会考虑重构遵循此模式的任何代码.有ICola提供一个描述方法,并让它自我描述.这避免了类型检查和重复代码......