我习惯于 C# 不执行溢出检查,正如语言规范所述 (§7.5.12):
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.
我在低级代码中进行数组边界检查时利用了这一点:
if ((uint)index >= (uint)TotalCount)
...
如果 index 为负数,我预计它会变成一个大的正数,从而超过 TotalCount。然而,令我惊讶的是,负数会产生 OverflowException,我必须将表达式包装在 unchecked() 中。我查看了 Visual Studio 中的项目选项,但没有看到启用或禁用溢出检查的选项。那么为什么它会出现在这里?
最佳答案
它应该在项目中。
- 双击“属性”文件夹。
- 构建选项卡。
- 单击“高级...”按钮。
- 取消选中“检查算术溢出/下溢”。
关于C# - 什么会导致溢出检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2328610/