c# - 为什么 CLR 不编译溢出 const 而编译变量呢?

标签 c# .net clr

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

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 .

关于c# - 为什么 CLR 不编译溢出 const 而编译变量呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13755566/

相关文章:

c# - ReactiveUI:IObservable.Transform() 不转发通知

c# - 如何使用 Linq 获取不在某个时间段内的前两个连续日期时间点?

.NET 线程处于 'pre-emptive GC disabled' 模式,会阻塞 GC 并可能导致死锁

c# - 使用 linq 按父级对对象列表进行分组以输出子元素

c# - 确保字符串不包含特定字符的快速方法

c# - MySQL 服务器可以从 C# 应用程序加载数据吗?

c# - Newtonsoft.Json.Schema.JsonSchema 已过时?

c# - DateTime.Today 和 "static readonly"

c# - 强制转换与在 CLR 中使用 'as' 关键字

c# - 在 C# 中获取 'ldftn' 函数指针