c#美味:使用checked語句防止資料溢出

來源:互聯網
上載者:User
文章目錄
  • checked
  •  
  • unchecked
  • 幾個注意
  • 參考資料

在C#中有一個關鍵字checked,它用來判斷當前上下文中的數值運算和數值轉換是否會溢出。如是是常量溢出,那在編譯時間就能發現;如果是變數溢出,那在運行時會拋出OverflowException。

數值運算有:++   —   - (unary)   +   -   *   /

 

有了這個就不用擔心資料溢出了。

 

checked

checked 有兩種使用方法:

1.作為操作符來使用

int a = int.MinValue;int c = checked(a--);

執行的時候會拋出異常:

2.檢查一大塊代碼

這樣子會對裡面所有的代碼都做檢查

checked{    int a = int.MinValue;    int c = a--;}

如:

 unchecked

和checked對應,還有一個unchecked關鍵字,用來取消檢查。

也是兩種使用;

1.作為運算子

int a = int.MinValue;int c = unchecked(a--);

這樣子就不會拋異常了

 

2.檢查一大塊代碼

unchecked{    int a = int.MinValue;    int c = a--;}

也不拋異常:

 

/checked 和/checked-


如果代碼裡總是要寫這麼多checked語句是不是很煩?如果能有一個編譯參數就好,只有設定了就都會檢查。微軟也想到了這個,它提供了一個/checked 參數來做,也提供了一個/checked-來取消。

  • 溢出檢查 /checked,也可以是/checked+
  • 溢出不檢查 /checked-

當然,你想取消所有的檢查也是可以的,命令列參數是/checked-

csc t2.cs /checked

其中csc是編譯器csc.exe , t2.cs 是被編譯的代碼檔案。

我想很多人是用Visual Studio吧。VS裡也是可以設定的。

步驟如下,我以VS2010為例,(VS2005,2008差不多)

1。在工程上點右鍵,選擇菜單Properties

2。點擊“Build”,再點擊“Advanced”

3。在開啟的對話方塊中,把“Check for arithmetic overflow/underflow”打上勾

幾個注意

1.checked語句只對當前上下文中的代碼有效,即不對調用的函數內部做檢查

static void Main(string[] args){    checked    {        TestFun();    }}static void TestFun(){    int a = int.MinValue;    int c = a--;}

這段代碼中。不會跑異常,因為checked關鍵字沒有影響到TestFun內部。如果需要這麼做的話,要麼在TestFun內部加checked關鍵字,要麼開啟全域開關(加編譯參數/checked或者VS中設定)。

2.checked,unchecked關鍵字不檢查左移和右移是否溢出。

static void Main(string[] args){    checked    {        int a = int.MinValue;        int c = a>>1;    }}

執行不會拋異常:

 

3.為了效能考慮,建議Debug時做檢查,Release時不做檢查。

 

參考資料

/checked (Check Integer Arithmetic)

http://msdn.microsoft.com/en-us/library/h25wtyxf(v=VS.71).aspx

Arithmetic Overflow Checking using checked/unchecked

http://www.codeproject.com/KB/cs/overflow_checking.aspx

C# 3.0 in a Nutshell, 3rd Edition

Chapter 2.4.5.2. Integral overflow

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.