来自文档:
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
is equivalent to:
expression is type ? (type)expression : (type) null
except that expression is evaluated only once.
那么,您为什么不选择以一种或另一种方式进行呢?为什么有两种类型转换系统?
最佳答案
它们不是两种类型转换系统。两者具有相似的 Action ,但含义却截然不同。 “as”的意思是“我认为这个对象可能实际上是另一种类型;如果不是,请给我 null。”强制转换意味着以下两种情况之一:
我确定这个对象实际上是另一种类型。这样做,如果我错了,让程序崩溃。
我确定这个对象不是其他类型,但是有一种众所周知的方法可以将当前类型的值转换为所需的类型。 (例如,将 int 转换为 short。)这样做,如果转换实际上不起作用,则使程序崩溃。
有关详细信息,请参阅我关于该主题的文章。
https://ericlippert.com/2009/10/08/whats-the-difference-between-as-and-cast-operators/
关于c# - C#中 "As"关键字有什么意义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3160127/