简体   繁体   English

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

[英]Arithmetic operations with 8 and 16 bit integers

I do understand why this produce compile time-error: 我确实理解为什么这会产生编译时错误:

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

I've grasped why this runs without any issues: 我已经理解了为什么运行时没有任何问题:

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

But I've got no clue why this also works: 但是我不知道为什么这也行得通:

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

I expected to get the same compile-time error as in the first example, but it runs successfully... Why? 我期望得到与第一个示例相同的编译时错误,但是它运行成功...为什么?

Since you're using constant values, the compiler can detect that it's allowable, evaluate it at compile time , and let it execute. 由于您使用的是常量值,因此编译器可以检测到它是允许的, 在编译时对其进行评估,然后让其执行。 The generated IL evaluates to the same as typing short x = 3; 生成的IL与输入short x = 3;的结果相同short x = 3; .

Note the following also works (for the same reason): 请注意,以下内容也可以工作(出于相同的原因):

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

But this fails: 但这失败了:

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

Note that this is covered in the C# Language Spec, 6.1.9 Implicit constant expression conversions: 请注意,C#语言规范6.1.9隐式常量表达式转换对此进行了介绍:

  • A constant-expression (§7.19) of type int can be converted to type sbyte, byte, short, ushort, uint, or ulong, provided the value of the constant-expression is within the range of the destination type. 可以将类型为int的常数表达式(第7.19节)转换为sbyte,byte,short,ushort,uint或ulong类型,前提是该常数表达式的值在目标类型的范围内。

Your last snippet just compiles to constant 3 . 您的最后一个片段只是编译为常数3 Compiler doesn't need to call any operators in int it just computes and stores the value at compile time. 编译器不需要在int调用任何运算符,它只是在编译时计算并存储值。

it is same as short x = 3; 它与short x = 3;相同short x = 3;

Here is the generated IL 这是生成的IL

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

I've got no clue why this also works: 我不知道为什么这也行得通:

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

The compiler evaluates the rhs expression at compile time and can prove that the result is within bounds. 编译器在编译时评估rhs表达式,并可以证明结果在范围之内。

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

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