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

标签 c# .net integer overflow

处理整数溢出是一项常见任务,但在 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# 关键字 unchecked,它的作用与 checked 正好相反,它会忽略溢出。您可能想知道什么时候会使用 unchecked,因为它似乎是默认行为。好吧,有一个 C# 编译器选项定义了如何处理 checkedunchecked 之外的表达式:/checked .您可以在项目的高级build设置下进行设置。

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

关于c# - 在 C# 中处理整数溢出的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2954970/

相关文章:

SQLite3 整数最大值

c# - 将 SqlDataType 转换为 C# 枚举

c# - 从返回 403 forbidden 的网站解析

python - 生成 3 位数的数字

c# - 模态进度表显示 IProgress 并支持取消 WinForms 的异步任务

.net - 在运行时从数据库呈现 ASPX 页面

c - C中没有减号的减法

c# - 从 WPF 窗体中的 Canvas 获取 UI 元素大小

c# - 使用 C# 将未知大小的 CSV 转换为自定义对象

c# - Npgsql:一个连接,多个命令