1. 程式人生 > 實用技巧 >【轉載】C# checked和unchecked關鍵字

【轉載】C# checked和unchecked關鍵字

--轉自微軟checked 關鍵字 - C# 參考 | Microsoft Docs/unchecked 關鍵字 - C# 參考 | Microsoft Docs

--本文版權歸微軟所有

一、checked關鍵字

checked關鍵字用於對整型型別算術運算和轉換顯式啟用溢位檢查。

預設情況下,如果表示式僅包含常量值,且產生的值在目標類型範圍之外,則會導致編譯器錯誤。如果表示式包含一個或多個非常量值,則編譯器不檢測溢位。在下面的示例中,計算賦給i2的表示式不會導致編譯器錯誤。

 1 // The following example causes compiler error CS0220 because 2147483647
2 // is the maximum value for integers. 3 //int i1 = 2147483647 + 10; 4 5 // The following example, which includes variable ten, does not cause 6 // a compiler error. 7 int ten = 10; 8 int i2 = 2147483647 + ten; 9 10 // By default, the overflow in the previous statement also does 11 // not cause a run-time exception. The following line displays
12 // -2,147,483,639 as the sum of 2,147,483,647 and 10. 13 Console.WriteLine(i2);

預設情況下,在執行時也不檢查這些非常量表達式是否溢位,這些表示式不引發溢位異常。上面的示例顯示 -2,147,483,639 作為兩個正整數之和。

可以通過編譯器選項、環境配置或使用checked關鍵字來啟用溢位檢查。下面的示例演示如何使用checked表示式或checked塊,在執行時檢測由前面的求和計算導致的溢位。兩個示例都引發溢位異常。

 1 // If the previous sum is attempted in a checked environment, an
2 // OverflowException error is raised. 3 4 // Checked expression. 5 Console.WriteLine(checked(2147483647 + ten)); 6 7 // Checked block. 8 checked 9 { 10 int i3 = 2147483647 + ten; 11 Console.WriteLine(i3); 12 }

可以使用unchecked關鍵字阻止溢位檢查。

示例

此示例演示如何使用checked啟用執行時溢位檢查。

 1 class OverFlowTest
 2 {
 3     // Set maxIntValue to the maximum value for integers.
 4     static int maxIntValue = 2147483647;
 5 
 6     // Using a checked expression.
 7     static int CheckedMethod()
 8     {
 9         int z = 0;
10         try
11         {
12             // The following line raises an exception because it is checked.
13             z = checked(maxIntValue + 10);
14         }
15         catch (System.OverflowException e)
16         {
17             // The following line displays information about the error.
18             Console.WriteLine("CHECKED and CAUGHT:  " + e.ToString());
19         }
20         // The value of z is still 0.
21         return z;
22     }
23 
24     // Using an unchecked expression.
25     static int UncheckedMethod()
26     {
27         int z = 0;
28         try
29         {
30             // The following calculation is unchecked and will not
31             // raise an exception.
32             z = maxIntValue + 10;
33         }
34         catch (System.OverflowException e)
35         {
36             // The following line will not be executed.
37             Console.WriteLine("UNCHECKED and CAUGHT:  " + e.ToString());
38         }
39         // Because of the undetected overflow, the sum of 2147483647 + 10 is
40         // returned as -2147483639.
41         return z;
42     }
43 
44     static void Main()
45     {
46         Console.WriteLine("\nCHECKED output value is: {0}",
47                           CheckedMethod());
48         Console.WriteLine("UNCHECKED output value is: {0}",
49                           UncheckedMethod());
50     }
51     /*
52    Output:
53    CHECKED and CAUGHT:  System.OverflowException: Arithmetic operation resulted
54    in an overflow.
55       at ConsoleApplication1.OverFlowTest.CheckedMethod()
56 
57    CHECKED output value is: 0
58    UNCHECKED output value is: -2147483639
59  */
60 }

二、unchecked關鍵字

unchecked關鍵字用於取消整型型別的算術運算和轉換的溢位檢查。

在未經檢查的上下文中,如果表示式生成的值超出目標型別的範圍,則不會標記溢位。例如,由於以下示例中的計算在unchecked塊或表示式中執行,因此將忽略計算結果對於整數而言過大的事實,並且向int1賦予值 -2,147,483,639。

1 unchecked
2 {
3     int1 = 2147483647 + 10;
4 }
5 int1 = unchecked(ConstantMax + 10);

如果刪除unchecked環境,會發生編譯錯誤。由於表示式的所有項都是常量,因此可在編譯時檢測到溢位。

在編譯時和執行時,預設不檢查包含非常數項的表示式。請參閱啟用檢查,獲取有關使用啟用了檢查的環境的資訊。

由於檢查溢位需要時間,因此在沒有溢位風險的情況下使用取消檢查的程式碼可能會提高效能。但是,如果存在溢位的可能,則應使用啟用了檢查的環境。

示例

此示例演示如何使用unchecked關鍵字。

 1 class UncheckedDemo
 2 {
 3     static void Main(string[] args)
 4     {
 5         // int.MaxValue is 2,147,483,647.
 6         const int ConstantMax = int.MaxValue;
 7         int int1;
 8         int int2;
 9         int variableMax = 2147483647;
10 
11         // The following statements are checked by default at compile time. They do not
12         // compile.
13         //int1 = 2147483647 + 10;
14         //int1 = ConstantMax + 10;
15 
16         // To enable the assignments to int1 to compile and run, place them inside
17         // an unchecked block or expression. The following statements compile and
18         // run.
19         unchecked
20         {
21             int1 = 2147483647 + 10;
22         }
23         int1 = unchecked(ConstantMax + 10);
24 
25         // The sum of 2,147,483,647 and 10 is displayed as -2,147,483,639.
26         Console.WriteLine(int1);
27 
28         // The following statement is unchecked by default at compile time and run
29         // time because the expression contains the variable variableMax. It causes
30         // overflow but the overflow is not detected. The statement compiles and runs.
31         int2 = variableMax + 10;
32 
33         // Again, the sum of 2,147,483,647 and 10 is displayed as -2,147,483,639.
34         Console.WriteLine(int2);
35 
36         // To catch the overflow in the assignment to int2 at run time, put the
37         // declaration in a checked block or expression. The following
38         // statements compile but raise an overflow exception at run time.
39         checked
40         {
41             //int2 = variableMax + 10;
42         }
43         //int2 = checked(variableMax + 10);
44 
45         // Unchecked sections frequently are used to break out of a checked
46         // environment in order to improve performance in a portion of code
47         // that is not expected to raise overflow exceptions.
48         checked
49         {
50             // Code that might cause overflow should be executed in a checked
51             // environment.
52             unchecked
53             {
54                 // This section is appropriate for code that you are confident
55                 // will not result in overflow, and for which performance is
56                 // a priority.
57             }
58             // Additional checked code here.
59         }
60     }
61 }

本文轉自微軟Docs,如有錯誤歡迎指正。