Fab*_*nda 6 .net c# oop types casting
假设我有一个对象的实例,我知道它属于通过C#中超类型的引用传递给我的某个子类型的子类,我习惯于看到类似Java的方式完成类型转换(假设"引用"是超类型):
if (reference is subtype){
subtype t = (subtype)reference;
}
Run Code Online (Sandbox Code Playgroud)
但是最近我遇到过这样做的例子:
if (reference is subtype){
subtype t = reference as subtype;
}
Run Code Online (Sandbox Code Playgroud)
这两个完全相同吗?有什么区别吗?
Fra*_* B. 11
不同之处在于,如果转换不正确,则会抛出异常而另一个将返回空值.此外,"as"关键字对值类型不起作用.
BaseType _object;
//throw an exception
AnotherType _casted = (AnotherType) _object;
//return null
AnotherType _casted = _object as AnotherType;
Run Code Online (Sandbox Code Playgroud)
编辑:
在Fabio de Miranda的示例中,由于使用了"is"关键字而无法输入"if"语句,因此不会抛出异常.
它们使用的方式相同,但两者都不是最好的选择.您应该只进行一次类型检查:
subtype t = reference as subtype;
if (t != null) {
...
}
Run Code Online (Sandbox Code Playgroud)
检查null比检查类型更有效.