对于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(){}'。主要的优点是可读性和异常安全性。 –