[C#][Tips]再探using陳述式

  • 15573
  • 0
  • C#
  • 2010-05-02

[C#][Tips]再探using陳述式

上一篇我大概介紹了什麼是using statement,簡單可以說using statement就是try finally的簡潔語法,

但我有些朋友卻認為using statement會吃掉所有例外狀況(try catch finally語法),

而之前在MSDN論壇上也有看到某些網友也支持這樣的說法,

所以這篇我就來驗證using statement到底是否有含catch。

 

我利用MSDN範列編譯成功後,比對IL中介碼來看看using statement是否真的包含catch。

Font font2 = new Font("Arial", 10.0f);
using( font2 )
{
    bool isbold = font2.Bold;
}

 

 

 

IL

image

 Font font2 = new Font( "Arial", 10.0f );
            try
            {
                bool isbold = font2.Bold;
            }
            finally
            {
                if( font2 != null )
                    font2.Dispose();
            }

  

 

 

IL 

image

可以看到兩種寫法的IL中介碼幾乎一模一樣,而且不包含catch。

 

來看看try catch finally後的IL中介碼

 Font font2 = new Font( "Arial", 10.0f );
            try
            {
                bool isbold = font2.Bold;
            }
            catch( Exception ex )
            { 
            }
            finally
            {
                if( font2 != null )
                    font2.Dispose();
            }

  

 

 

IL

image

透過IL中介碼我們可以知道using statement真的不包含catch,所以千萬不要在誤會使用using stement會吃掉所有例外狀況。

 

上一篇我也提到如果要捕抓例外狀況須自行加入try catch,我們也來看看C#編譯器會輸出什麼樣的程式碼。

 Font font2 = new Font( "Arial", 10.0f );
            using( font2 )
            {
                try
                {
                    bool isbold = font2.Bold;
                }
                catch( Exception ex )
                {
                }
            }

  

 

 

image image

可以看到使用using statement+try catch後,就如同使用try catch finally。

 

再補充using statement注意事項:

1.由於會隱含執行Dispose,所以不需要再手動處理,如果自己在手動執行Close()、Dispose(),

  只會讓CLR再度浪費資源進而影響程式效能。

 

參考

SQL Server Connection Pooling (ADO.NET)