处理整数溢出是一项常见任务,但在 C# 中处理它的最佳方法是什么?是否有一些语法糖使它比其他语言更简单?或者这真的是最好的方法吗?
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!");
我不需要经常使用这个,但是你可以使用 checked 关键字:
I haven't needed to use this often, but you can use the checked keyword:
int x = foo();
int test = checked(x * common);
如果溢出将导致运行时异常.来自 MSDN:
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.
我还应该指出,还有另一个 C# 关键字,unchecked
,它当然与 checked
相反并且忽略溢出.您可能想知道您何时使用过 unchecked
,因为它似乎是默认行为.好吧,有一个 C# 编译器选项定义了如何处理 checked
和 unchecked
之外的表达式:/checked.您可以在项目的高级构建设置下进行设置.
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.
如果您有很多表达式需要检查,最简单的做法实际上是设置 /checked
构建选项.那么任何溢出的表达式,除非包含在 unchecked
中,都会导致运行时异常.
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# 中处理整数溢出的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!