C#的+=运算符两例
2009-06-03 08:30:34 来源:WEB开发网the intuitive reason for each error is that a corresponding simple assignment would also have been an error. end example]
[Note: Compound assignment operations support lifted operators. Since a compound assignment x op= y is evaluated as either x = x op y or x = (T)(x op y), the rules of evaluation implicitly cover lifted operators. end note]
14.14.3 Event assignment
If the left operand of a += or -= operator is an event, the expression is classified as an event access, and is evaluated as follows:
The instance expression, if any, of the event access is evaluated.
The right operand of the += or -= operator is evaluated, and, if required, converted to the type of the left operand through an implicit conversion (§13.1).
An event accessor of the event is invoked, with argument list consisting of the value computed in the previous step. If the operator was +=, the add accessor is invoked; if the operator was -=, the remove accessor is invoked.
An event assignment expression does not yield a value. Thus, an event assignment expression is valid only in the context of a statement-expression (§15.6).
C#中复合赋值运算符比Java规定了更多的转换相关规则,不过还是可以很直观的理解:(注意上面用蓝色色高亮的那句)只有当x op y和x = y都是合法的时候,x op= y才是合法的。
也正是因为这样,所以justjavac提到的Java的两个陷阱在C#里都不存在:
1、编译错误:
C#代码
static class Program {
static void Main(string[] args) {
byte b = 0;
int i = 1;
b += i; // error CS0266: 无法将类型“int”隐式转换为“byte”。存在一个显式转换(是否缺少强制转换?)
}
}
不用像Java那样等到运行的时候再发现数据被剪了。
2、编译没问题,运行也没问题:
C#代码
using System;
using System.Linq.Expressions;
static class Program {
static void Main(string[] args) {
string s = "str: ";
object obj = (Expression<Func<int, int>>) (x => x + 1);
s += obj;
obj += s;
Console.WriteLine(s); // str: x => (x + 1)
Console.WriteLine(obj); // x => (x + 1)str: x => (x + 1)
}
}
- ››C的学习方法
- ››C的数据库编程(2)
- ››运算符优先级
- ››运算符总结
更多精彩
赞助商链接