"As"的含义是什么? C#中的关键字 [英] What's the point of "As" keyword in C#

查看:80
本文介绍了"As"的含义是什么? C#中的关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从文档中:

as运算符与强制转换类似,只是它在转换失败时产生null而不是引发异常.更正式地说,是以下形式的表达式:

The as operator is like a cast except that it yields null on conversion failure instead of raising an exception. More formally, an expression of the form:

   expression as type

等效于:

  expression is type ? (type)expression : (type) null

除了该表达式只计算一次.

except that expression is evaluated only once.

那么您为什么不选择以一种或另一种方式来做.为什么要有两个铸造系统?

So why wouldn't you choose to either do it one way or the other. Why have two systems of casting?

推荐答案

它们不是两个强制转换的系统.两者的作用相似,但含义却大不相同. "as"表示我认为此对象可能实际上是另一种类型;如果不是,请给我null".强制转换意味着两件事之一:

They aren't two system of casting. The two have similar actions but very different meanings. An "as" means "I think this object might actually be of this other type; give me null if it isn't." A cast means one of two things:

  • 我确定该对象实际上是其他类型.这样做,如果我错了,请使程序崩溃.

  • I know for sure that this object actually is of this other type. Make it so, and if I'm wrong, crash the program.

我肯定知道该对象不是其他类型,但是有一种众所周知的方法可以将当前类型的值转换为所需类型. (例如,将int转换为short.)这样做,如果转换实际上不起作用,则使程序崩溃.

I know for sure that this object is not of this other type, but that there is a well-known way of converting the value of the current type to the desired type. (For example, casting int to short.) Make it so, and if the conversion doesn't actually work, crash the program.

有关更多信息,请参阅我关于该主题的文章.

See my article on the subject for more details.

http://blogs.msdn.com/b/ericlippert/archive/2009/10/08/what-s-the-difference-between-as-and-cast-operators.aspx

这篇关于"As"的含义是什么? C#中的关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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