2013-09-28 23 views
2

對於C#我還是比較陌生,並且只在過去的幾天內才暴露給「IDisposables」。我可以掌握using塊的概念,以照顧必須處理的物體,而無需手動記住撥打.Dispose()方法 - 方便!在另一個IDisposable中處理IDisposables「使用」語句

讓我們假設,雖然我從一個新的SqlConnection開始,我在using聲明中處理。在該代碼塊中,我創建了一些額外的IDisposables,例如SqlDataAdapter。該適配器是否需要它自己的using聲明?

例如,如果我有代碼...

using (SqlConnection myConnection = new SqlConnection()) 
{ 
    SqlCommand myCommand = new SqlCommand(); 
    SqlDataAdapter myAdapter = new SqlDataAdapter(); 
    // Do things 
} 

...將myCommandmyAdapter被設置時myConnection設置的(因爲它們是代碼塊的範圍內的)?或者我需要多using語句,也許是這樣的:using語句

using (SqlConnection myConnection = new SqlConnection()) 
{ 
    using (SqlCommand myCommand = new SqlCommand()) 
    { 
     using (SqlDataAdapter myAdapter = new SqlDataAdapter()) 
     { 
      // Do things 
     } 
    } 
} 
+1

是你使用塊,使每個對象處理函數被調用需要多個在使用塊結束的範圍。 – dbw

+1

請注意,需要記住Dispose()只是需要記住'using(){}'。主要的優點是可讀性和異常安全性。 –

回答

7

嚴格地說嵌套語法糖,它確實是最好的處置所有其中。但是,您可以通過直接嵌套他們避免縮進:

using (var myConnection = new SqlConnection()) 
using (var myCommand = new SqlCommand()) 
using (var myAdapter = new SqlDataAdapter()) 
{ 
    // Do things 
} 

另外,特別是在ADO.NET的情況下(這不,讓我們的是公平的,有很多一次性類型的),你可能會發現更容易使用該隱藏了很多管道的圖書館之一 - 例如,與「短小精悍」:

using(var conn = new SqlConnection(...)) 
{ 
    return conn.Query<Customer>(
     "select * from Customers where [email protected]", 
     new { region }).ToList(); 
} 
3

這是否適配器需要它自己的?

在這種情況下,沒有。但是,這取決於連接和適配器對象的詳細知識,例如最佳實踐:使用一個using()IDisposable。即使對於MemoryStream Dispose()什麼都不做。它們便宜。

你的代碼是正確的,但我們平時節約的{}

using (SqlConnection myConnection = new SqlConnection()) 
using (SqlCommand myCommand = new SqlCommand())  
using (SqlDataAdapter myAdapter = new SqlDataAdapter()) 
{ 
    // Do things 
} 

我們在這裏使用的規則,當一個using()控制1個語句(下一using()),你不需要花括號。然後我們對縮進進行一點修改。

0

使用僅僅是

  var connection = new Connection(); 
     try 
     { 
      connection.DoSomething(); 
     } 
     finally 
     { 
      // Check for a null resource. 
      if (connection != null) 
      { 
       ((IDisposable)connection).Dispose(); 
      } 
     } 

所以,是的,您需要使用語句一定要處理所有這些

相關問題