繁体   English   中英

8位和16位整数的算术运算

[英]Arithmetic operations with 8 and 16 bit integers

我确实理解为什么这会产生编译时错误:

short x = 1;
short y = 2;
short z = x + y; // compile-time error

我已经理解了为什么运行时没有任何问题:

short x = 1;
short y = 2;
x += y; // all right, because of c# specs section 7.17.2

但是我不知道为什么这也行得通:

short x = (short)1 + (short)2;

我期望得到与第一个示例相同的编译时错误,但是它运行成功...为什么?

由于您使用的是常量值,因此编译器可以检测到它是允许的, 在编译时对其进行评估,然后让其执行。 生成的IL与输入short x = 3;的结果相同short x = 3;

请注意,以下内容也可以工作(出于相同的原因):

const short x = 1;
const short y = 2;
short z = x + y; 

但这失败了:

const short x = 32000;
const short y = 32001;
short z = x + y;

请注意,C#语言规范6.1.9隐式常量表达式转换对此进行了介绍:

  • 可以将类型为int的常数表达式(第7.19节)转换为sbyte,byte,short,ushort,uint或ulong类型,前提是该常数表达式的值在目标类型的范围内。

您的最后一个片段只是编译为常数3 编译器不需要在int调用任何运算符,它只是在编译时计算并存储值。

它与short x = 3;相同short x = 3;

这是生成的IL

IL_0001:  ldc.i4.3    //Load the constant 3 into evaluation stack
IL_0002:  stloc.0     // stores the value in stack to x

我不知道为什么这也行得通:

 short x = (short)1 + (short)2; 

编译器在编译时评估rhs表达式,并可以证明结果在范围之内。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM