铸造:(NEWTYPE)与对象为NE​​WTYPE [英] Casting: (NewType) vs. Object as NewType

查看:127
本文介绍了铸造:(NEWTYPE)与对象为NE​​WTYPE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

什么是实际上这两种类型转换之间的区别是什么?

What is actually the difference between these two casts?

SomeClass sc = (SomeClass)SomeObject;
SomeClass sc2 = SomeObject as SomeClass;

通常情况下,他们都应该是显式类型转换为指定的类型?

Normally, they should both be explicit casts to the specified type?

推荐答案

,前者将抛出一个异常,如果源类型无法转换为目标类型。后者将导致SC2是一个空引用,但也不例外。

The former will throw an exception if the source type can't be cast to the target type. The latter will result in sc2 being a null reference, but no exception.

我原来的答案当然是最明显的区别,但作为埃里克利珀<一href="http://blogs.msdn.com/ericlippert/archive/2009/10/08/what-s-the-difference-between-as-and-cast-operators.aspx">points出,它不是唯一的一个。其他区别包括:

My original answer is certainly the most pronounced difference, but as Eric Lippert points out, it's not the only one. Other differences include:

  • 您不能使用为经营者投以不接受'零'作为值
  • 系统类型
  • 您不能使用'作为'来的转换的东西,如数字到不同的重新presentation(浮动为int,例如)。
  • You can't use the 'as' operator to cast to a type that doesn't accept 'null' as a value
  • You can't use 'as' to convert things, like numbers to a different representation (float to int, for example).

最后,用为与强制转换运算符,你也说:我不知道这是否会成功。

And finally, using 'as' vs. the cast operator, you're also saying "I'm not sure if this will succeed."

这篇关于铸造:(NEWTYPE)与对象为NE​​WTYPE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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