C#" AS"投VS铸经典 [英] C# "as" cast vs classic cast

查看:158
本文介绍了C#" AS"投VS铸经典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  铸造VS使用'为'在CLR

最近,我学到了不同的方式来投。而不是用

I recently learned about a different way to cast. Rather than using

SomeClass someObject = (SomeClass) obj;

可以使用以下语法:

one can use this syntax:

SomeClass someObject = obj as SomeClass;

这似乎返回null如果obj不是一个SomeClass的,而不是抛出一个类转换异常。

which seems to return null if obj isn't a SomeClass, rather than throwing a class cast exception.

我看到,这可能会导致一个NullReferenceException如果转换失败,我尝试访问someObject变量。所以,我想知道这是什么方法背后的原因是什么?为什么要使用铸造,而不是(旧)的这种途径之一 - 它只是似乎移动的问题未能投更深入到code

I see that this can lead to a NullReferenceException if the cast failed and I try to access the someObject variable. So I'm wondering what's the rationale behind this method? Why should one use this way of casting rather than the (old) one - it only seems to move the problem of a failed cast "deeper" into the code.

推荐答案

通过经典的方法,如果转换失败,抛出一个异常。与AS方法,它导致空值,这可以为进行检查,避免抛出异常。

With the "classic" method, if the cast fails, an exception is thrown. With the as method, it results in null, which can be checked for, and avoid an exception being thrown.

此外,你只能用为引用类型,所以如果你值映射为一个值类型,你仍然必须使用经典的方法。

Also, you can only use "as" with reference types, so if you are typecasting to a value type, you must still use the "classic" method.

编辑:

由于这个答案正在变得流行,我想我会纠正previous第(感谢那些谁评论,并指出了这一点给我)。在方法只能用于那些可分配值类型。这使用只意味着引用类型,但是当.NET 2.0出来了,它引入了一个空值类型的概念。由于这些类型的可分配价值,它们是有效的操作者使用。

Since this answer is becoming popular, I thought I would correct the previous paragraph (thanks to those who commented and pointed this out to me). The as method can only be used for types that can be assigned a null value. That use to only mean reference types, but when .NET 2.0 came out, it introduced the concept of a nullable value type. Since these types can be assigned a null value, they are valid to use with the as operator.

这篇关于C#" AS"投VS铸经典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆