unchecked(C# 参考)

unchecked 关键字用于取消整型算术运算和转换的溢出检查。

在未检查的上下文中,如果表达式产生的值在目标类型范围之外,并不会标记溢出。例如,下例中的计算在 unchecked 块或表达式中执行,因此将忽略结果对于整数而言过大这一事实,并会对 int1 赋予值 -2,147,483,639。

unchecked
{
    int1 = 2147483647 + 10;
}
int1 = unchecked(ConstantMax + 10);

如果移除 unchecked 环境,则发生编译错误。因为表达式的各个项都是常数,所以可以在编译时检测到溢出。

默认情况下,在编译时和运行时不检查包含非常数项的表达式。有关启用检查环境的信息,请参见 checked(C# 参考)

因为溢出检查比较耗时,所以当无溢出危险时,使用不检查的代码可以提高性能。但是,如果可能发生溢出,则应使用检查环境。

此示例演示如何使用 unchecked 关键字。

class UncheckedDemo
{
    static void Main(string[] args)
    {
        // int.MaxValue is 2,147,483,647.
        const int ConstantMax = int.MaxValue;
        int int1;
        int int2;
        int variableMax = 2147483647;

        // The following statements are checked by default at compile time. They do not
        // compile.
        //int1 = 2147483647 + 10;
        //int1 = ConstantMax + 10;

        // To enable the assignments to int1 to compile and run, place them inside 
        // an unchecked block or expression. The following statements compile and
        // run.
        unchecked
        {
            int1 = 2147483647 + 10;
        }
        int1 = unchecked(ConstantMax + 10);

        // The sum of 2,147,483,647 and 10 is displayed as -2,147,483,639.
        Console.WriteLine(int1);

        // The following statement is unchecked by default at compile time and run 
        // time because the expression contains the variable variableMax. It causes  
        // overflow but the overflow is not detected. The statement compiles and runs.
        int2 = variableMax + 10;

        // Again, the sum of 2,147,483,647 and 10 is displayed as -2,147,483,639.
        Console.WriteLine(int2);

        // To catch the overflow in the assignment to int2 at run time, put the
        // declaration in a checked block or expression. The following
        // statements compile but raise an overflow exception at run time.
        checked
        {
            //int2 = variableMax + 10;
        }
        //int2 = checked(variableMax + 10);

        // Unchecked sections frequently are used to break out of a checked 
        // environment in order to improve performance in a portion of code 
        // that is not expected to raise overflow exceptions.
        checked
        { 
            // Code that might cause overflow should be executed in a checked
            // environment.
            unchecked
            { 
                // This section is appropriate for code that you are confident 
                // will not result in overflow, and for which performance is 
                // a priority.
            }
            // Additional checked code here. 
        }
    }
}

C# 语言规范

有关详细信息,请参阅 C# 语言规范。该语言规范是 C# 语法和用法的权威资料。

请参阅

C# 参考

C# 编程指南

C# 关键字

Checked 和 Unchecked(C# 参考)

checked(C# 参考)