Checked 和 Unchecked(C# 参考)Checked and Unchecked (C# Reference)

C# 语句既可以在已检查的上下文中执行,也可以在未检查的上下文中执行。C# statements can execute in either checked or unchecked context. 在已检查的上下文中,算法溢出引发异常。In a checked context, arithmetic overflow raises an exception. 在未选中的上下文中忽略算术溢出并将结果截断,方法是:丢弃任何不适应目标类型的高序位。In an unchecked context, arithmetic overflow is ignored and the result is truncated by discarding any high-order bits that don't fit in the destination type.

下列操作受溢出检查的影响:The following operations are affected by the overflow checking:

  • 表达式在整型上使用下列预定义运算符:Expressions using the following predefined operators on integral types:

    ++--,一元 -+-*/++, --, unary -, +, -, *, /

  • 整型类型之间或从 floatdouble 到整型类型的显式数字转换。Explicit numeric conversions between integral types, or from float or double to an integral type.

如果既未指定 checked,也未指定 unchecked,则非常量表达式(在运行时计算的表达式)的默认上下文将由 -checked 编译器选项的值定义。If neither checked nor unchecked is specified, the default context for non-constant expressions (expressions that are evaluated at run time) is defined by the value of the -checked compiler option. 默认情况下,该选项的值未设置,且算术运算在未选中的上下文中执行。By default the value of that option is unset and arithmetic operations are executed in an unchecked context.

对于常量表达式(可在编译时完全计算的表达式),将始终选中默认上下文。For constant expressions (expressions that can be fully evaluated at compile time), the default context is always checked. 除非在未选中的上下文中显式放置常量表达式,否则在编译时间计算表达式过程中出现的溢出将导致编译时错误。Unless a constant expression is explicitly placed in an unchecked context, overflows that occur during the compile-time evaluation of the expression cause compile-time errors.

请参阅See also