對於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
}
...將myCommand
和myAdapter
被設置時myConnection
設置的(因爲它們是代碼塊的範圍內的)?或者我需要多using
語句,也許是這樣的:using語句
using (SqlConnection myConnection = new SqlConnection())
{
using (SqlCommand myCommand = new SqlCommand())
{
using (SqlDataAdapter myAdapter = new SqlDataAdapter())
{
// Do things
}
}
}
是你使用塊,使每個對象處理函數被調用需要多個在使用塊結束的範圍。 – dbw
請注意,需要記住Dispose()只是需要記住'using(){}'。主要的優點是可讀性和異常安全性。 –