checked (C# 參考)checked (C# Reference)

checked 關鍵字是用來明確啟用整數型別算術運算和轉換的溢位檢查。The checked keyword is used to explicitly enable overflow checking for integral-type arithmetic operations and conversions.

根據預設,如果運算式產生超出目的地類型範圍的值,則只包含常數值的運算式會導致編譯器錯誤。By default, an expression that contains only constant values causes a compiler error if the expression produces a value that is outside the range of the destination type. 如果運算式包含一或多個非常數值,則編譯器偵測不到溢位。If the expression contains one or more non-constant values, the compiler does not detect the overflow. 評估下列範例中指派給 i2 的運算式不會導致編譯器錯誤。Evaluating the expression assigned to i2 in the following example does not cause a compiler error.

// The following example causes compiler error CS0220 because 2147483647
// is the maximum value for integers. 
//int i1 = 2147483647 + 10;

// The following example, which includes variable ten, does not cause
// a compiler error.
int ten = 10;
int i2 = 2147483647 + ten;

// By default, the overflow in the previous statement also does
// not cause a run-time exception. The following line displays 
// -2,147,483,639 as the sum of 2,147,483,647 and 10.
Console.WriteLine(i2);

根據預設,不會檢查這些非常數運算式是否在執行階段溢位,而且它們不會引發溢位例外狀況。By default, these non-constant expressions are not checked for overflow at run time either, and they do not raise overflow exceptions. 先前的範例會顯示 -2,147,483,639 作為兩個正整數的總和。The previous example displays -2,147,483,639 as the sum of two positive integers.

可以透過編譯器選項、環境設定或使用 checked 關鍵字來啟用溢位檢查。Overflow checking can be enabled by compiler options, environment configuration, or use of the checked keyword. 下列範例示範如何使用 checked 運算式或 checked 區塊,來偵測先前的總和在執行階段所產生的溢位。The following examples demonstrate how to use a checked expression or a checked block to detect the overflow that is produced by the previous sum at run time. 這兩個範例都會引發溢位例外狀況。Both examples raise an overflow exception.

// If the previous sum is attempted in a checked environment, an 
// OverflowException error is raised.

// Checked expression.
Console.WriteLine(checked(2147483647 + ten));

// Checked block.
checked
{
    int i3 = 2147483647 + ten;
    Console.WriteLine(i3);
}

unchecked 關鍵字可以用來防止溢位檢查。The unchecked keyword can be used to prevent overflow checking.

範例Example

這個範例示範如何使用 checked,以在執行階段啟用溢位檢查。This sample shows how to use checked to enable overflow checking at run time.

class OverFlowTest
{
    // Set maxIntValue to the maximum value for integers.
    static int maxIntValue = 2147483647;

    // Using a checked expression.
    static int CheckedMethod()
    {
        int z = 0;
        try
        {
            // The following line raises an exception because it is checked.
            z = checked(maxIntValue + 10);
        }
        catch (System.OverflowException e)
        {
            // The following line displays information about the error.
            Console.WriteLine("CHECKED and CAUGHT:  " + e.ToString());
        }
        // The value of z is still 0.
        return z;
    }

    // Using an unchecked expression.
    static int UncheckedMethod()
    {
        int z = 0;
        try
        {
            // The following calculation is unchecked and will not 
            // raise an exception.
            z = maxIntValue + 10;
        }
        catch (System.OverflowException e)
        {
            // The following line will not be executed.
            Console.WriteLine("UNCHECKED and CAUGHT:  " + e.ToString());
        }
        // Because of the undetected overflow, the sum of 2147483647 + 10 is 
        // returned as -2147483639.
        return z;
    }

    static void Main()
    {
        Console.WriteLine("\nCHECKED output value is: {0}",
                          CheckedMethod());
        Console.WriteLine("UNCHECKED output value is: {0}",
                          UncheckedMethod());
    }
    /*
   Output:
   CHECKED and CAUGHT:  System.OverflowException: Arithmetic operation resulted
   in an overflow.
      at ConsoleApplication1.OverFlowTest.CheckedMethod() 

   CHECKED output value is: 0
   UNCHECKED output value is: -2147483639
 */
}

C# 語言規格C# language specification

如需詳細資訊,請參閱<C# 語言規格>。For more information, see the C# Language Specification. 語言規格是 C# 語法及用法的限定來源。The language specification is the definitive source for C# syntax and usage.

請參閱See also