处理整数溢出是一项常见任务,但在 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# 编译器选项定义了如何处理 checked
和 unchecked
之外的表达式:/checked .您可以在项目的高级build设置下进行设置。
如果您有很多表达式需要检查,最简单的做法实际上是设置 /checked
构建选项。那么任何溢出的表达式,除非包含在 unchecked
中,否则将导致运行时异常。
关于c# - 在 C# 中处理整数溢出的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2954970/