本文以實例形式對比測試了C#中checked和unchecked的區別,對于C#初學者來說有很好的借鑒參考價值。具體分析如下:
int類型的最大值是2147483647,2個最大值相加就會超出int的最大值,即出現溢出。
class Program { static void Main(string[] args) { int y = 2147483647; int x = 2147483647; int z = x + y; Console.WriteLine(z.ToString()); Console.ReadKey(); } }
把斷點打在 int z = x + y;代碼行,單步調試,可以看到z的值為-2。因為int類型的最大值是2147483647,x + y超出了最大值,出現了溢出。
程序運行效果如下圖所示:
一、使用checked:
如果我們想讓編譯器幫我們判斷是否溢出,就使用checked關鍵字。
class Program { static void Main(string[] args) { int y = 2147483647; int x = 2147483647; int z = checked(x + y); } }
運行后拋出溢出異常,運行結果如下圖所示:
如果我們想手動捕獲并打印異常,應該這樣寫:
class Program { static void Main(string[] args) { int y = 2147483647; int x = 2147483647; try { int z = checked(x + y); } catch (OverflowException ex) { Console.WriteLine(ex.Message); } Console.ReadKey(); } }
運行結果如下圖所示:
二、使用unchecked:
使用unchecked不會拋出溢出異常。
class Program { static void Main(string[] args) { int y = 2147483647; int x = 2147483647; int z = unchecked(x + y); Console.WriteLine(z.ToString()); Console.ReadKey(); } }
結果為:-2
新聞熱點
疑難解答