const int cMax = int.MaxValue;
int vMax = cMax;
int int1;
int int2;
int1 = cMax + 10;//Checked amd throws error
int2 = vMax+10;//Unchecked and Overflows at runTime
这里可以看到涉及常量的操作默认是被检查的,而涉及变量的操作是未检查的并且通过了编译。
为什么编译行为会出现这种差异?
最佳答案
行为不同,因为 cMax + 10
是常量表达式。根据C# Language Reference ,
A constant expression is an expression that can be fully evaluated at compile time. A constant can participate in a constant expression, as follows:
public const int c1 = 5; public const int c2 = c1 + 100;
By default, an expression that contains only constant values causes a compiler error if the expression produces a value that is outside the range of the destination type. If the expression contains one or more non-constant values, the compiler does not detect the overflow.
因此,编译器必须在编译时评估您的表达式。由于它无法生成有效值作为计算结果,因此会产生编译时错误。使用 checked
keyword启用整数溢出检查。
关于C# 变量和常量在溢出期间的行为不同。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50310220/