在 C# 中处理整数溢出的最佳方法?

发布于 2024-09-04 01:06:07 字数 233 浏览 3 评论 0原文

处理整数溢出是一项常见任务,但在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

情感失落者 2024-09-11 01:06:07

我不需要经常使用它,但您可以使用 checked 关键字:

int x = foo();
int test = checked(x * common);

如果溢出将导致运行时异常。来自 MSDN:

在检查的上下文中,如果表达式生成的值是
超出目标类型的范围,结果取决于
表达式是常量还是非常量。持续的
表达式会导致编译时错误,而非常量表达式
在运行时评估并引发异常。

我还应该指出,还有另一个 C# 关键字,unchecked,它的作用当然与 checked 相反,并且忽略溢出。您可能想知道什么时候会使用unchecked,因为它似乎是默认行为。嗯,有一个 C# 编译器选项定义了如何处理 checkedunchecked 之外的表达式:/checked。您可以在项目的高级构建设置下进行设置。

如果您有很多需要检查的表达式,最简单的做法实际上是设置 /checked 构建选项。那么任何溢出的表达式,除非用 unchecked 包装,都会导致运行时异常。

I haven't needed to use this often, but you can use the checked keyword:

int x = foo();
int test = checked(x * common);

Will result in a runtime exception if overflows. From MSDN:

In a checked context, if an expression produces a value that is
outside the range of the destination type, the result depends on
whether the expression is constant or non-constant. Constant
expressions cause compile time errors, while non-constant expressions
are evaluated at run time and raise exceptions.

I should also point out that there is another C# keyword, unchecked, which of course does the opposite of checked and ignores overflows. You might wonder when you'd ever use unchecked since it appears to be the default behavior. Well, there is a C# compiler option that defines how expressions outside of checked and unchecked 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 in unchecked, would result in a runtime exception.

深居我梦 2024-09-11 01:06:07

尝试以下操作

int x = foo();
try {
  int test = checked (x * common);
  Console.WriteLine("safe!");
} catch (OverflowException) {
  Console.WriteLine("oh noes!");
}

Try the following

int x = foo();
try {
  int test = checked (x * common);
  Console.WriteLine("safe!");
} catch (OverflowException) {
  Console.WriteLine("oh noes!");
}
雨巷深深 2024-09-11 01:06:07

最好的方法是正如 Micheal 所说 - 使用 Checked 关键字。
这可以这样做:

int x = int.MaxValue;
try   
{
    checked
    {
        int test = x * 2;
        Console.WriteLine("No Overflow!");
    }
}
catch (OverflowException ex)
{
   Console.WriteLine("Overflow Exception caught as: " + ex.ToString());
}

The best way is as Micheal Said - use Checked keyword.
This can be done as :

int x = int.MaxValue;
try   
{
    checked
    {
        int test = x * 2;
        Console.WriteLine("No Overflow!");
    }
}
catch (OverflowException ex)
{
   Console.WriteLine("Overflow Exception caught as: " + ex.ToString());
}
青衫负雪 2024-09-11 01:06:07

有时,最简单方法就是最好方法。我想不出更好的方法来编写您所写的内容,但您可以将其简短为:

int x = foo();

if ((x * common) / common != x)
    Console.WriteLine("oh noes!");
else
    Console.WriteLine("safe!");

请注意,我没有删除 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:

int x = foo();

if ((x * common) / common != x)
    Console.WriteLine("oh noes!");
else
    Console.WriteLine("safe!");

Note that I didn't remove the x variable because it'd be foolish to call the foo() three times.

人生百味 2024-09-11 01:06:07

老线程,但我刚刚遇到这个。我不想使用异常。我最终得到的是:

long a = (long)b * (long)c;
if(a>int.MaxValue || a<int.MinValue)
    do whatever you want with the overflow
return((int)a);

Old thread, but I just ran into this. I didn't want to use exceptions. What I ended up with was:

long a = (long)b * (long)c;
if(a>int.MaxValue || a<int.MinValue)
    do whatever you want with the overflow
return((int)a);
短暂陪伴 2024-09-11 01:06:07

所以,我在事后遇到了这个问题,它主要回答了我的问题,但对于我的特殊情况(如果其他人有相同的要求),我想要任何会溢出有符号 int 的正值的东西结算于int.MaxValue

int x = int.MaxValue - 3;
int someval = foo();

try
{
   x += someval;
}

catch (OverflowException)
{
   x = 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:

int x = int.MaxValue - 3;
int someval = foo();

try
{
   x += someval;
}

catch (OverflowException)
{
   x = int.MaxValue;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文