2010-10-26 122 views
12

根據MSDN Library混淆使用「使用」聲明C#

using Statement (C# Reference)
Defines a scope, outside of which an object or objects will be disposed.

但我得到這個代碼一些用戶張貼在這裏,我弄糊塗了這一點:(請參閱我的代碼註釋)

using (OleDBConnection connection = new OleDBConnection(connectiongString)) 
      { 
       if (connection.State != ConnectionState.Open) 
        connection.Open(); 
       string sql = "INSERT INTO Student (Id, Name) VALUES (@idParameter, @nameParameter)"; 

       using (OleDBCommand command = connection.CreateCommand()) 
       { 
        command.CommandText = sql; 
        command.CommandType = CommandType.Text; 

        OleDBParameter idParameter = command.CreateParameter(); 
        idParameter.DbType = System.Int32; 
        idParameter.Direction = Parameterdirection.Input; 
        idParameter.Name = "@idParameter"; 
        idParameter.Value = studentId; 

        OleDBParameter nameParameter = command.CreateParameter(); 
        try 
        { 
         command.ExecuteNonQuery(); 
        } 
        finally 
        { 
         // Is it still necessary to dispose these objects here? 
         command.Dispose(); 
         connection.Dispose(); 
        } 
       } 
      } 

在上面的代碼中,是否正確使用了using語句? 我很困惑,任何人都可以請解釋如何使用using聲明及其範圍以及何時何地使用它。謝謝。

回答

10

using語句是手動放置try/finally塊的簡寫。

所以

using(x){ 
    ... 
} 

相同

try{ 
    ... 
}finally{ 
    if(x != null){ x.Dispose(); } 
} 

並編譯時,他們會產生相同的IL。

如果x沒有執行IDisposable,編譯器會給你一個錯誤。

+0

實際上與if(x!= null){((IDisposable)x)相同。 } - 使用語句(C#參考)http://bit.ly/acmoOD – 2010-10-26 11:01:40

+0

我感到很難過,因爲我在你有一分鐘​​前發佈了我的答案(當前)是兩倍票數,這對於SO來說並不好,你的問題並不遜於我的,但是因爲你沒有足夠快的速度,它可能不會超過我的。 – Motti 2010-10-26 12:39:52

+0

這就是目前我工作的方式,而且我不確定是否有快速「修復」。可悲的是,它促進了快速的回答,而不是經過深思熟慮的回答。我發現自己經常寫一個快速的答案,即使我知道我將需要稍後編輯它,以不完全沉沒。我已經考慮了一段時間,我的一個建議是,在發佈問題後,10分鐘內不會顯示答案,然後在10分鐘後,所有在此時間範圍內寫入的答案都會以隨機順序顯示相同的時間戳。可能是一個好主意;) – 2010-10-26 13:36:59

11

finally塊(因此在這種情況下try)是多餘的,這就是using做,它與它的初始化IDisposable對象調用Disposeusing塊結束時(無論異常或缺乏)。