看到下面的代码,我只是想了解背后的原因......
const int a = 2147483647;
const int b = 2147483647;
int c = a + b; // it doesn't allow to compile!!!
int a = 2147483647;
int b = 2147483647;
int c = a + b; // it allows to compile!!!
最佳答案
const
表达式在编译时解析,非 const
表达式在运行时解析。默认情况下,每个都有不同类型的溢出检查上下文。根据 C# 规范:
For non-constant expressions (expressions that are evaluated at run-time) that are not enclosed by any checked or unchecked operators or statements, the default overflow checking context is unchecked unless external factors (such as compiler switches and execution environment configuration) call for checked evaluation.
这就是为什么在使用局部变量进行算术运算时看不到运行时错误的原因。至于const
计算:
For constant expressions (expressions that can be fully evaluated at compile-time), the default overflow checking context is always checked. Unless a constant expression is explicitly placed in an unchecked context, overflows that occur during the compile-time evaluation of the expression always cause compile-time errors.
这就是您在 const
计算中看到编译时错误的原因。
关于c# - 为什么 CLR 不编译溢出 const 而编译变量呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13755566/