WEB开发网
开发学院软件开发C语言 C#的+=运算符两例 阅读

C#的+=运算符两例

 2009-06-03 08:30:34 来源:WEB开发网   
核心提示:刚偶尔看到了justjavac写的java解惑 - 半斤八两(一)和java解惑 - 半斤八两(二),里面提到了Java的复合赋值运算符的两个陷阱:1) 复合赋值运算符有强制类型转换的语义;2) += 左侧必须是原始类型中的数字类型,C#的+=运算符两例,或者是String类型, JLS3e如是说: Java Lang

刚偶尔看到了justjavac写的java解惑 - 半斤八两(一)和java解惑 - 半斤八两(二)。里面提到了Java的复合赋值运算符的两个陷阱:1) 复合赋值运算符有强制类型转换的语义;2) += 左侧必须是原始类型中的数字类型,或者是String类型。

JLS3e如是说:

Java Language Specification, 3rd Edition 写道

15.26.2 Compound Assignment Operators

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

核心就这么一句,后面还有一堆细节规定,有兴趣可以到官网阅读:JLS3e: 15.26.2 Compound Assignment Operators

读下来,只有当复合赋值运算符的左手边是数组,且数组元素类型是String时才有提到特别针对String的+=,在15.26.2的其它地方并没有提到justjavac说的第二个限制,怪哉。

ECMA-334如是说:

ECMA-334, 4th Edition 写道

14.14.2 Compound assignment

An operation of the form x op= y is processed by applying binary operator overload resolution (§14.2.4) as if the operation was written x op y. Then,  

If the return type of the selected operator is implicitly convertible to the type of x, the operation is evaluated as x = x op y, except that x is evaluated only once.

Otherwise, if the selected operator is a predefined operator, if the return type of the selected operator is explicitly convertible to the type of x, and if y is implicitly convertible to the type of x or the operator is a shift operator, then the operation is evaluated as x = (T)(x op y), where T is the type of x, except that x is evaluated only once.

1 2 3  下一页

Tags:运算符

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接