14.6.6 Cast expressions

A cast-expression is used to explicitly convert an expression to a given
type.
cast-expression:
( type ) unary-expression
A cast-expression of the form (T)E, where T is a type and E is a
unary-expression, performs an explicit
conversion (?3.2) of the value of E to type T. If no explicit conversion
exists from the type of E to T, a
compile-time error occurs. Otherwise, the result is the value produced by
the explicit conversion. The result
is always classified as a value, even if E denotes a variable.
C# LANGUAGE SPECIFICATION
156
The grammar for a cast-expression leads to certain syntactic ambiguities.
[Example: For example, the
expression (x)?y could either be interpreted as a cast-expression (a cast
of ?y to type x) or as an additiveexpression
combined with a parenthesized-expression (which computes the value x ? y).
end example]
To resolve cast-expression ambiguities, the following rule exists: A
sequence of one or more tokens (?.4)
enclosed in parentheses is considered the start of a cast-expression only
if at least one of the following are
true:
?The sequence of tokens is correct grammar for a type, but not for an
expression.
?The sequence of tokens is correct grammar for a type, and the token
immediately following the closing
parentheses is the token ?~?, the token ?!?, the token ?(?, an identifier (?
.4.1), a literal (?.4.4), or any
keyword (?.4.3) except as and is.
The term ?correct grammar? above means only that the sequence of tokens
must conform to the particular
grammatical production. It specifically does not consider the actual
meaning of any constituent identifiers.
[Example: For example, if x and y are identifiers, then x.y is correct
grammar for a type, even if x.y
doesn?t actually denote a type. end example]
[Note: From the disambiguation rule, it follows that, if x and y are
identifiers, (x)y, (x)(y), and (x)(-y)
are cast-expressions, but (x)-y is not, even if x identifies a type.
However, if x is a keyword that identifies
a predefined type (such as int), then all four forms are cast-expressions
(because such a keyword could not
possibly be an expression by itself). end note]
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值