处理整数溢出在C#中的最佳方法是什么? [英] Best way to handle Integer overflow in C#?

查看:374
本文介绍了处理整数溢出在C#中的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

处理整数溢出是一种常见的任务,但什么是处理在C#中的最佳方法是什么?有一些语法糖,使其比其他语言更简单?还是这真的是最好的方法是什么?

  INT X = FOO();
INT试验= X *常见;
如果(测试/常见!= X)
    Console.WriteLine(哦不一!);
其他
    Console.WriteLine(安全!);
 

解决方案

我还没有使用这种经常需要的,但你可以使用的checked 关键字:

  INT X = FOO();
INT测试=检查(X *常见);
 

将导致运行时异常,如果溢出。从MSDN:

在checked上下文中,如果前女友pression产生的值是目标类型的范围之外时,结果取决于EX pression是否恒定或不恒定的恒恩pressions导致编译时错误,而非常量的前pressions在运行时评估并引发异常。

我还应该指出的是,还有另外一个C#的关键字,选中,这当然不相反检查并忽略溢出。你可能不知道,当你曾经使用选中,因为它似乎是默认的行为。那么,有一个定义如何EX pressions外检查选中正在处理的C#编译器选项: /检查。您可以设置它在你的项目的高级构建设置。

如果你有很多需要进行检查前pressions,做最简单的做法实际上是将 /检查构建选项。那么任何EX pression溢出,除非包裹在选中,将导致运行时异常。

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!");

解决方案

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.

这篇关于处理整数溢出在C#中的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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