C# 程序:
short a, b;
a = 10;
b = 10;
a = a + b; // Error : Cannot implicitly convert type 'int' to 'short'.
// we can also write this code by using Arithmetic Assignment Operator as given below
a += b; // But this is running successfully, why?
Console.Write(a);
最佳答案
这里有两个问题。第一个是“为什么short加short的结果是int?”
好吧,假设 short 加 short 是 short,看看会发生什么:
short[] prices = { 10000, 15000, 11000 };
short average = (prices[0] + prices[1] + prices[2]) / 3;
如果这个计算是在空头中进行的,那么平均值当然是 -9845。总和大于最大可能的短路,因此它环绕为负数,然后除以负数。
在整数运算环绕的世界中,在 int 中进行所有计算更为明智,这种类型可能有足够的范围让典型计算不会溢出。
第二个问题是:
- short 加 short 是 int
- 将 int 赋值给 short 是非法的
- a +=b 等同于 a = a + b
- 因此 short += short 应该是非法的
- 那么为什么这是合法的?
问题的前提不正确;上面第三行是错误的。 C# 规范在第 7.17.2 节中声明
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.
编译器代表您插入转换。正确的推理是:
- short 加 short 是 int
- 将 int 赋值给 short 是非法的
- s1 += s2 等同于 s1 = (short)(s1 + s2)
- 因此这应该是合法的
如果它没有为您插入强制转换,那么就不可能对多种类型使用复合赋值。
关于c# - 整数求和布鲁斯,short += short 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4343624/