c# - as和cast的比较

标签 c# .net

<分区>

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/

相关文章:

c# - C#中的字数统计算法

c# - 在 XML 中搜索元素

c# - 将此行从 C++ 转换为 C#

c# - nhibernate 使用先前的状态创建

c# - 比较 2 字符串

c# - 使用 MVC 过滤器的国际化问题

c# - 如何创建 Excel 行并将其插入 Excel 范围?

c# - 如何在 EF 查询中将 Uint 转换为 Nullable Int

.net - 如何更改我的 Web 方法调用的 http 版本以停止 505 错误?

c# - 任务完成后更改文本框值