c# – 为什么CLR不编译溢出const,但是对于变量它呢?

看下面的代码,我只是想了解背后的原因……

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计算出现编译时错误的原因.

More information about checked and unchecked on MSDN.

上一篇:单片机汇编之查找最大数


下一篇:直接提供WSDL文件引入服务