探討c#中的unchecked是什么意思,起什么作用?
更新時間:2013年06月05日 11:58:17 作者:
本篇文章是對c#中的unchecked進行了詳細的分析介紹,需要的朋友參考下
Checked與Unchecked
對于因為整數(shù)類型參與算術(shù)操作和類型轉(zhuǎn)換時產(chǎn)生的“溢出異?!薄猄ystem.OverflowException,在某些算法來講不算真正的“異?!保喾催@種溢出常常為程序所用。C#通過引入checked和unchecked關(guān)鍵字來控制這種特殊情況的需求。它們都可以加于一個語句塊前(如:checked{……}),或者一個算術(shù)表達式前(如:unchecked(x+y)),其中加checked標志的語句或表達式如果發(fā)生算術(shù)溢出,則拋出System.OverflowException類型的異常,而加unchecked標志的語句發(fā)生算術(shù)溢出時,則不拋出異常。下面是一個示例:
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
可以看到同樣的算術(shù)操作,用checked拋出了溢出異常,而unchecked只是將溢出的位丟棄而得到剩下的32位組成的十進制整數(shù)值。值得指出的是可以用“/checked”編譯器選項指定整個文件的代碼為checked語義,如果沒有指定則默認為unchecked。如果同時在程序代碼中指定checked或unchecked標志,又有了checked編譯器選項,則除了標志為unchecked的代碼外,其余的都有checked語義。
對于因為整數(shù)類型參與算術(shù)操作和類型轉(zhuǎn)換時產(chǎn)生的“溢出異?!薄猄ystem.OverflowException,在某些算法來講不算真正的“異?!保喾催@種溢出常常為程序所用。C#通過引入checked和unchecked關(guān)鍵字來控制這種特殊情況的需求。它們都可以加于一個語句塊前(如:checked{……}),或者一個算術(shù)表達式前(如:unchecked(x+y)),其中加checked標志的語句或表達式如果發(fā)生算術(shù)溢出,則拋出System.OverflowException類型的異常,而加unchecked標志的語句發(fā)生算術(shù)溢出時,則不拋出異常。下面是一個示例:
復(fù)制代碼 代碼如下:
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);}
}
}
}
程序輸出:
復(fù)制代碼 代碼如下:
System.OverflowException: Arithmetic operation resulted in an overflow.
at Test.Main()
0
1410065408
可以看到同樣的算術(shù)操作,用checked拋出了溢出異常,而unchecked只是將溢出的位丟棄而得到剩下的32位組成的十進制整數(shù)值。值得指出的是可以用“/checked”編譯器選項指定整個文件的代碼為checked語義,如果沒有指定則默認為unchecked。如果同時在程序代碼中指定checked或unchecked標志,又有了checked編譯器選項,則除了標志為unchecked的代碼外,其余的都有checked語義。
相關(guān)文章
C# 中的 IReadOnlyDictionary 和 IReadOnlyLis
C# 中的IReadOnlyDictionary和IReadOnlyList是接口,用于表示只讀的字典和只讀的列表,這些接口提供了對集合的只讀訪問權(quán)限,即不允許對集合進行修改操作,這篇文章主要介紹了C# 中的 IReadOnlyDictionary 和 IReadOnlyList實例詳解,需要的朋友可以參考下2024-03-03