开发者

Based on what precedence rules is a[x].SomeMember evaluated as (a[x]).SomeMember and not…?

开发者 https://www.devze.com 2022-12-19 16:01 出处:网络
a) Both dot operator ( a.x ) and index operator ( a[x] ) have the same level of precedence. So based on what precedence rules is an expression a[x].SomeMember evaluated as (a[x]).SomeMember and not as

a) Both dot operator ( a.x ) and index operator ( a[x] ) have the same level of precedence. So based on what precedence rules is an expression a[x].SomeMember evaluated as (a[x]).SomeMember and not as (a.SomeMember )[x]?

b) Is casting operator开发者_JAVA技巧 an unary operator ( and thus has lower precedence than dot operator ) and for that reason is an expression (int)a.xevaluated as (int)(a.x)?

thank you


For a)

From C# Specification, section 7.2.1:

When an operand occurs between two operators with the same precedence, the associativity of the operators controls the order in which the operations are performed:

  • Except for the assignment operators, all binary operators are left-associative, meaning that operations are performed from left to right. For example, x + y + z is evaluated as (x + y) + z.
  • The assignment operators and the conditional operator (?:) are right-associative, meaning that operations are performed from right to left. For example, x = y = z is evaluated as x = (y = z).

This means that the operators will get precedence, in this situation, from left to right.

b) Yes, this is correct. This is a Cast Expression, described in section 7.6.6, which is applied to a unary expression, and casts are categorized with the Unary operators (Section 7.6) and treated with the same precedence.


a) The precedence is a left-to-right precedence. In evaluating the references, the compiler proceeds left to right in determining which equal operators receive precedence. Since a[x] precedes [x].SomeMember it gets referenced first.

b) It is not a unary operator but it has the same precedence as a unary.

Precedence of the C# Operators


a) Based on the sequence of code. a = b is interpreted differently to b = a for the same reason!

b) Casting is an unary operator as described here. Its specific behaviour is explained here.

0

精彩评论

暂无评论...
验证码 换一张
取 消