【发布时间】:2013-09-28 23:13:56
【问题描述】:
我对 C# 还是比较陌生,并且只是在过去几天内接触过“IDisposables”。我可以掌握using 块的概念来处理必须处理的对象,而无需手动记住调用.Dispose() 方法 - 方便!
假设我从一个新的SqlConnection 开始,我在using 语句中处理它。在该代码块中,我创建了一些额外的 IDisposable,例如 SqlDataAdapter。该适配器是否需要它自己的 using 语句?
例如,如果我有代码...
using (SqlConnection myConnection = new SqlConnection())
{
SqlCommand myCommand = new SqlCommand();
SqlDataAdapter myAdapter = new SqlDataAdapter();
// Do things
}
...myCommand 和 myAdapter 会在 myConnection 被处理时被处理(因为它们在该代码块的范围内)?还是我需要多个using 语句,可能类似于:
using (SqlConnection myConnection = new SqlConnection())
{
using (SqlCommand myCommand = new SqlCommand())
{
using (SqlDataAdapter myAdapter = new SqlDataAdapter())
{
// Do things
}
}
}
【问题讨论】:
-
是的,您需要多个 using 块,以便在 using 块的范围结束时调用每个对象的 dispose 函数。
-
请注意,需要记住 Dispose() 只是转移到需要记住
using() {}。这样做的主要优点是可读性和异常安全性。
标签: c#