什么时候必须在C#中使用checked操作符?

mas*_*ani 14 c# operators checked

什么时候必须checked在C#中使用运算符?
它只适用于异常处理吗?

Hen*_*man 14

您将使用checked来防止表达式中的(静默)溢出.
并使用unchecked,当你知道会发生一种无害的溢出.

您可以在不希望依赖默认(项目范围)编译器设置的位置使用它们.

这两种形式都非常罕见,但在进行关键整数运算时,值得考虑可能的溢出.

另请注意,它们有两种形式:

 x = unchecked(x + 1);    // ( expression )
 unchecked { x = x + 1;}  // { statement(s) }
Run Code Online (Sandbox Code Playgroud)


Asa*_*sad 6

checked将帮助你拿起System.OverFlowException哪些将被忽视的否则

int result = checked (1000000 * 10000000);   
    // Error: operation > overflows at compile time

int result = unchecked (1000000 * 10000000);  
    // No problems, compiles fine
Run Code Online (Sandbox Code Playgroud)