【发布时间】:2011-03-08 21:48:47
【问题描述】:
我在 VS 2010 中的 DAL 中有很多类似的方法。当我运行“新”代码分析选项时,我收到消息 - 警告 CA2000 对象 'comm' 未沿所有异常路径处理。在对对象“comm”的所有引用超出范围之前调用 System.IDisposable.Dispose。
我知道我可以为 SQLCommand 使用另一个 using 语句,但是如果我喜欢像使用 Try/Finally 块那样做的话。我的理解是 finally 块最后执行并进行清理。有人在这里看到我的 dispose 调用有什么问题吗?
public List<Product> GetAllProducts()
{
List<Product> prodList = new List<Product>();
using (SqlConnection connection = new SqlConnection(GetConnection()))
{
SqlCommand comm = new SqlCommand("GetAllProducts", connection);
connection.Open();
comm.CommandType = CommandType.StoredProcedure;
SqlDataReader dr = comm.ExecuteReader();
try
{
while (dr.Read())
{
Product obj = new Product();
obj.ProductID = Convert.ToInt32(dr["ProductID"].ToString());
obj.Product = dr["Product"].ToString();
//etc....
prodList.Add(obj);
}
}
finally
{
comm.Dispose();
dr.Close();
}
}
return prodList;
}
}
【问题讨论】: