Checked與Unchecked
對於因為整數類型參與算術操作和類型轉換時產生的“溢出異常”——System.OverflowException,在某些演算法來講不算真正的“異常”,相反這種溢出常常為程式所用。C#通過引入checked和unchecked關鍵字來控制這種特殊情況的需求。它們都可以加於一個語句塊前(如:checked{……}),或者一個算術運算式前(如:unchecked(x+y)),其中加checked標誌的語句或運算式如果發生算術溢位,則拋出System.OverflowException類型的異常,而加unchecked標誌的語句發生算術溢位時,則不拋出異常。下面是一個樣本:
複製代碼 代碼如下: using System;
class Test{
static void Main() {
int num1=100000,num2=100000,
result=0;
checked{ try { result= num1 * num2;}
catch(System.Overflo2wException e){ Console.WriteLine(e); }
finally{ Console.WriteLine(result);}
}
unchecked{ try { result= num1 * num2;}
catch(System.OverflowException (e){ Console.WriteLine(e);}
finally{ Console.WriteLine(result);}
}
}
}
程式輸出: 複製代碼 代碼如下:
System.OverflowException: Arithmetic operation resulted in an overflow.
at Test.Main()
0
1410065408
可以看到同樣的算術操作,用checked拋出了溢出異常,而unchecked只是將溢出的位丟棄而得到剩下的32位組成的十進位整數值。值得指出的是可以用“/checked”編譯器選項指定整個檔案的代碼為checked語義,如果沒有指定則預設為unchecked。如果同時在程式碼中指定checked或unchecked標誌,又有了checked編譯器選項,則除了標誌為unchecked的代碼外,其餘的都有checked語義。