在 C# 中处理整数溢出的最佳方法?
处理整数溢出是一项常见任务,但在 C# 中处理它的最佳方法是什么?是否有一些语法糖可以使其比其他语言更简单?或者这真的是最好的方法吗?
int x = foo();
int test = x * common;
if(test / common != x)
Console.WriteLine("oh noes!");
else
Console.WriteLine("safe!");
Handling integer overflow is a common task, but what's the best way to handle it in C#? Is there some syntactic sugar to make it simpler than with other languages? Or is this really the best way?
int x = foo();
int test = x * common;
if(test / common != x)
Console.WriteLine("oh noes!");
else
Console.WriteLine("safe!");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我不需要经常使用它,但您可以使用 checked 关键字:
如果溢出将导致运行时异常。来自 MSDN:
我还应该指出,还有另一个 C# 关键字,
unchecked
,它的作用当然与checked
相反,并且忽略溢出。您可能想知道什么时候会使用unchecked
,因为它似乎是默认行为。嗯,有一个 C# 编译器选项定义了如何处理checked
和unchecked
之外的表达式:/checked。您可以在项目的高级构建设置下进行设置。如果您有很多需要检查的表达式,最简单的做法实际上是设置
/checked
构建选项。那么任何溢出的表达式,除非用unchecked
包装,都会导致运行时异常。I haven't needed to use this often, but you can use the checked keyword:
Will result in a runtime exception if overflows. From MSDN:
I should also point out that there is another C# keyword,
unchecked
, which of course does the opposite ofchecked
and ignores overflows. You might wonder when you'd ever useunchecked
since it appears to be the default behavior. Well, there is a C# compiler option that defines how expressions outside ofchecked
andunchecked
are handled: /checked. You can set it under the advanced build settings of your project.If you have a lot of expressions that need to be checked, the simplest thing to do would actually be to set the
/checked
build option. Then any expression that overflows, unless wrapped inunchecked
, would result in a runtime exception.尝试以下操作
Try the following
最好的方法是正如 Micheal 所说 - 使用 Checked 关键字。
这可以这样做:
The best way is as Micheal Said - use Checked keyword.
This can be done as :
有时,最简单方法就是最好方法。我想不出更好的方法来编写您所写的内容,但您可以将其简短为:
请注意,我没有删除
x
变量,因为调用是愚蠢的foo()
三次。Sometimes, the simplest way is the best way. I can't think a better way to write what you wrote, but you can short it to:
Note that I didn't remove the
x
variable because it'd be foolish to call thefoo()
three times.老线程,但我刚刚遇到这个。我不想使用异常。我最终得到的是:
Old thread, but I just ran into this. I didn't want to use exceptions. What I ended up with was:
所以,我在事后遇到了这个问题,它主要回答了我的问题,但对于我的特殊情况(如果其他人有相同的要求),我想要任何会溢出有符号 int 的正值的东西结算于
int.MaxValue
:So, I ran into this far after the fact, and it mostly answered my question, but for my particular case (in the event anyone else has the same requirements), I wanted anything that would overflow the positive value of a signed int to just settle at
int.MaxValue
: