<分区>
Possible Duplicate:
Direct casting vs 'as' operator?
谁能比较一下as和cast?
最佳答案
如果被转换的对象不是请求的类型,直接转换将失败。 as
-cast 将返回 null。例如:
object obj = new object();
string str = (string)obj; // Throws ClassCastException
但是:
object obj = new object();
string str = obj as string; // Sets str to null
当被转换的对象是您要转换成的类型时,两种语法的结果是相同的:对象被成功转换。
请特别注意,您应该避免“as-and-invoke”模式:
(something as SomeType).Foo();
因为如果转换失败,您将抛出 NullReferenceException 而不是 ClassCastException。这可能会导致您追查 something
为 null 的原因,而实际上它不是!更丑陋但更好的代码
((SomeType)something).Foo();
当 something
引用的对象无法转换为 SomeType
时将抛出 ClassCastException,当 something
为 null 时将抛出 NullReferenceException。
关于c# - as和cast的比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4191780/