c# - 整数求和布鲁斯,short += short 问题

标签 c# types int short

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/

相关文章:

c - sscanf 似乎在 uint 变量和 c 中的 int 变量上表现不同

c# - "Unable to cast object of type ' ConcreteTypeMapping ' to type ' Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping"WebApi on macos

c# - 他们是在调整大小时阻止图片框闪烁的方法吗?

c# - 使用 ExecuteNonQueryAsync 和报告进度

java - 我可以在模板排序中使用简单类型吗

c程序将一个int分配给一个bool?

c# - 在锁定文件中找不到所需的信息。确保你的目标中提到了 .NETCore,Version=v5.0/win10-anycpu

c - 在 C 中打印类型转换类型

scala - Scala 中动态类型的实际用途

java - 如何将 Int 转换为无符号字节并返回