为什么C#默认不使用算术溢出检查? [英] Why doesn't C# use arithmetic overflow checking by default?

查看:107
本文介绍了为什么C#默认不使用算术溢出检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
默认情况下为什么语言不引发整数溢出错误?

Possible Duplicate:
Why don’t languages raise errors on integer overflow by default?

默认情况下,C#为什么不使用算术溢出检查?

我认为,发生异常通常会更好,这样就不会掩盖错误.我知道偶尔利用发生的包装"行为很有用,但是在这些情况下可以使用unchecked关键字来明确意图.

I figure that it would generally be better to have exceptions occur when this occurs so that errors aren't obscured. I know that it's occasionally useful to take advantage of the 'wrapping' behaviour that occurs, but the unchecked keyword could be used in these circumstances to make the intentions explicit.

我希望这个决定是有意做出的,也许是为了增加与其他基于C语言的兼容性.

I expect that this decision was made intentionally, perhaps to increase compatibility with other C-based languages.

推荐答案

C#语言规范说:

对于非恒定表达式(在以下位置计算的表达式 运行时),没有被任何checkedunchecked运算符包围 或语句,默认的溢出检查上下文为unchecked 除非外部因素(例如编译器切换和执行) 环境配置)进行checked评估.

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.

选择该选项的原因可能是性能.我同意这一决定会导致那些不了解静默"整数溢出的错误.

The reason for this choice is probably performance. I agree that this decision leads to errors among those who are not aware of "silent" integer overflow.

如果您的C#文件属于C#项目文件(*.csproj),则该文件包含默认"溢出检查上下文的配置.若要对其进行更改,请参见要在Visual Studio开发环境中设置此编译器选项 ="noreferrer">此页面.

If your C# files belong to a C# project file (*.csproj), then that file holds configuration of the "default" overflow checking context. To changed it, see To set this compiler option in the Visual Studio development environment in this page.

如果您不使用.csproj文件,则可能是从命令行编译了所有内容,然后上一页告诉您使用哪个命令行选项来设置默认的溢出检查上下文.

If you don't use .csproj files, you're probably compiling everything from the command line, and then the above page tells you what command line option to use to set the default overflow checking context.

这篇关于为什么C#默认不使用算术溢出检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆