探討c#中的unchecked是什麼意思,起什麼作用?

來源:互聯網
上載者:User

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語義。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.