2012-03-23 57 views
1

我发现在C#中a + = 1不等于a = a + 1。C#中a + = 1和a = a + 1的区别

例如,以下代码编译时没有任何错误: byte b = 10; b + = 5;

while while following code has a compilation error: byte b = 10; b = b + 5;

有人可以让我知道为什么吗?

+0

错误消息始终有帮助 – 2012-03-23 04:43:47

+0

错误消息是:“不能将类型'int'隐式转换为'byte'。存在明确的转换(您是否缺少转换?)” – Morteza 2012-03-23 04:47:11

+0

请参见:http:// stackoverflow。 COM /问题/ 4343624 /整数加法布鲁斯 - 短 - 短 - 问题 – 2012-03-23 04:47:30

回答

7

因为b + 5成为一个整数(的Int32)(主要是因为有过载的可能性)

和下面的化合物分配规范规定:

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.

0

编译器可能是治疗5作为一个Int32在第二个。你需要投它

1

因为b += 5编译好像它读取b = (byte)(b + 5)。演员负责转换到正确的类型,所以没有错误。

相关问题