妥善处理变量。使用语句是否足够?
Properly disposing of variable. Are using statements enough?
我有一个 class,其中包含调用存储过程的方法。其中一些存储过程 return 数据结构,另一些则没有。这是其中一种方法的示例。
public DataTable GetProductData(int productID)
{
DataTable dataTable = new DataTable();
using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter())
{
using (SqlConnection sqlConn = new SqlConnection("CONNECTIONSTRING"))
{
using (SqlCommand sqlCmd = new SqlCommand("getProductData", sqlConn))
{
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("@ID", productID);
sqlConn.Open();
sqlDataAdapter.Fill(dataTable);
}
}
}
return dataTable;
}
当需要访问数据时,另一个程序使用此方法。这是使用上述方法的方法示例 ...
public DataTable GetProductInfoFromDatabase(int productID)
{
DataLibrary dl = new DataLibrary();
return dl.GetProductData(productID);
}
我想知道的是,一旦检索到数据,我应该如何处理 dl
变量。垃圾回收会处理它还是我应该在定义 GetProductData
方法的 class 中实现 IDisposable? using
语句是否足够?
除非您的class持有非托管资源或其他IDisposable
对象; no,不需要自己实现IDisposable
。一个空的 Dispose
方法不会给你带来 任何东西。
在您提供的代码中,using
语句就足够了。在 GetProductInfoFromDatabase
中创建的 DataLibrary
对象将按您的预期被 GC 收集。
我有一个 class,其中包含调用存储过程的方法。其中一些存储过程 return 数据结构,另一些则没有。这是其中一种方法的示例。
public DataTable GetProductData(int productID)
{
DataTable dataTable = new DataTable();
using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter())
{
using (SqlConnection sqlConn = new SqlConnection("CONNECTIONSTRING"))
{
using (SqlCommand sqlCmd = new SqlCommand("getProductData", sqlConn))
{
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("@ID", productID);
sqlConn.Open();
sqlDataAdapter.Fill(dataTable);
}
}
}
return dataTable;
}
当需要访问数据时,另一个程序使用此方法。这是使用上述方法的方法示例 ...
public DataTable GetProductInfoFromDatabase(int productID)
{
DataLibrary dl = new DataLibrary();
return dl.GetProductData(productID);
}
我想知道的是,一旦检索到数据,我应该如何处理 dl
变量。垃圾回收会处理它还是我应该在定义 GetProductData
方法的 class 中实现 IDisposable? using
语句是否足够?
除非您的class持有非托管资源或其他IDisposable
对象; no,不需要自己实现IDisposable
。一个空的 Dispose
方法不会给你带来 任何东西。
在您提供的代码中,using
语句就足够了。在 GetProductInfoFromDatabase
中创建的 DataLibrary
对象将按您的预期被 GC 收集。