假设我有一个对象的实例,我知道它属于通过 C# 中父类(super class)型的引用传递给我的某个子类型的子类,我习惯于看到类型转换以类似 Java 的方式完成(假设“reference"属于父类(super class)型):
if (reference is subtype){
subtype t = (subtype)reference;
}
但最近我遇到了这样的例子:
if (reference is subtype){
subtype t = reference as subtype;
}
这两个是完全等价的吗?有区别吗?
最佳答案
不同之处在于,如果转换不正确,一个将抛出异常,另一个将返回空值。此外,“as”关键字不适用于值类型。
BaseType _object;
//throw an exception
AnotherType _casted = (AnotherType) _object;
//return null
AnotherType _casted = _object as AnotherType;
编辑:
在 Fabio de Miranda 的示例中,由于使用了“is”关键字阻止进入“if”语句,因此不会抛出异常。
关于C#: "(subtype)data"和 "data as subtype"类型转换之间有什么区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1168386/