14.9.10 The as operator

本文详细解析了C#中的as运算符工作原理及其使用场景。as运算符用于显式地将值转换为引用类型,不会抛出异常,而是返回null。文章探讨了不同情况下的类型转换过程。
The as operator is used to explicitly convert a value to a given reference
type using a reference conversion
or a boxing conversion. Unlike a cast expression (?4.6.6), the as operator
never throws an exception.
Instead, if the indicated conversion is not possible, the resulting value
is null.
In an operation of the form e as T, e must be an expression and T must be a
reference type. The type of the
result is T, and the result is always classified as a value. The operation
is evaluated as follows:
?If the compile-time type of e is the same as T, the result is simply the
value of e.
?Otherwise, if an implicit reference conversion (?3.1.4) or boxing
conversion (?3.1.5) exists from the
compile-time type of e to T, this conversion is performed and becomes the
result of the operation.
?Otherwise, if an explicit reference conversion (?3.2.3) exists from the
compile-time type of e to T, a
dynamic type check is performed:
If the value of e is null, the result is the value null with the
compile-time type T.
Chapter 14 Expressions
169
Otherwise, let R be the run-time type of the instance referenced by e. If R
and T are the same type, if R is a
reference type and an implicit reference conversion from R to T exists, or
if R is a value type and T is an
interface type that is implemented by R, the result is the reference given
by e with the compile-time type T.
Otherwise, the result is the value null with the compile-time type T.
?Otherwise, the indicated conversion is never possible, and a compile-time
error occurs.
The as operator only performs reference conversions and boxing conversions.
Other conversions, such as
user defined conversions, are not possible with the as operator and should
instead be performed using cast
expressions.
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值