C# - 什么可能导致此处溢出检查?
我习惯 C# 不执行溢出检查,如语言规范所述(第 7.5.12 节):
对于没有被任何已检查或未检查的运算符或语句括起来的非常量表达式(在运行时计算的表达式),默认的溢出检查上下文是未检查的,除非外部因素(例如编译器切换和执行环境配置) )要求进行检查评估。
我在低级代码中进行数组边界检查时利用了这一点:
if ((uint)index >= (uint)TotalCount)
...
如果索引为负数,我希望它成为一个大的正数,以便它超过 TotalCount。然而,令我惊讶的是,负数会产生 OverflowException,我必须将表达式包装在 unchecked() 中。我查看了 Visual Studio 中的项目选项,但没有看到启用或禁用溢出检查的选项。那么为什么它会出现在这里呢?
I am accustomed to C# not performing overflow checks, as the language spec states (§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.
I took advantage of this when doing an array bounds check in low-level code:
if ((uint)index >= (uint)TotalCount)
...
If index is negative, I expect it to become a large positive number so that it exceeds TotalCount. However, to my surprise, a negative number produces OverflowException, and I have to wrap the expression in unchecked(). I looked through the project options in Visual Studio and I do not see an option to enable or disable overflow checking. So why might it be on here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
应该是在项目里。
It should be in the project.