加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 01:22:11 所属栏目:百科 来源:网络整理
导读:处理整数溢出是一项常见任务,但在C#中处理它的最佳方法是什么?是否有一些语法糖比其他语言更简单?或者这真的是最好的方式吗? int x = foo();int test = x * common;if(test / common != x) Console.WriteLine("oh noes!");else Console.WriteLine("safe!"
处理整数溢出是一项常见任务,但在C#中处理它的最佳方法是什么?是否有一些语法糖比其他语言更简单?或者这真的是最好的方式吗?

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

解决方法

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

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

如果溢出,将导致运行时异常.来自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.

我还应该指出,还有另一个C#关键字,未经检查,当然与检查相反并忽略溢出.您可能想知道何时使用未选中状态,因为它似乎是默认行为.好吧,有一个C#编译器选项,它定义了如何处理checked和unchecked之外的表达式:/checked.您可以在项目的高级构建设置下设置它.

如果你有很多需要检查的表达式,最简单的事情就是设置/ checked构建选项.然后,任何溢出的表达式,除非未经检查包装,否则将导致运行时异常.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读