在进行 IO 工作时,我编写代码expect一个例外。
SqlConnection conn = null;
SqlCommand cmd = null;
try
{
conn = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString)
cmd = new SqlCommand(reportDataSource, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@Year", SqlDbType.Char, 4).Value = year;
cmd.Parameters.Add("@startDate", SqlDbType.DateTime).Value = start;
cmd.Parameters.Add("@endDate", SqlDbType.DateTime).Value = end;
conn.Open(); //opens connection
DataSet dset = new DataSet();
new SqlDataAdapter(cmd).Fill(dset);
this.gridDataSource.DataSource = dset.Tables[0];
}
catch(Exception ex)
{
Logger.Log(ex);
throw;
}
finally
{
if(conn != null)
conn.Dispose();
if(cmd != null)
cmd.Dispose();
}
Edit:明确地说,我避免using在这里阻止是因为我认为在这种情况下登录很重要。经验告诉我,你永远不知道会出现什么样的奇怪异常。记录这种情况可能会帮助您检测死锁,或者找到架构更改在哪里影响代码库中很少使用和很少测试的部分,或者任何其他问题。
Edit 2:有人可能会说,在这种情况下,using 块可以包装 try/catch,这是完全有效的,并且在功能上是等效的。这实际上可以归结为偏好。您是否想以自己处理垃圾为代价来避免额外的嵌套?或者您是否会产生额外的嵌套以进行自动处置。我觉得前者更干净,所以我就这样做。但是,如果我在我正在工作的代码库中找到后者,我不会重写它。
Edit 3:我真的非常希望 MS 创建了一个更明确的 using() 版本,使其更直观地了解实际发生的情况,并在这种情况下提供更大的灵活性。考虑以下虚构代码:
SqlConnection conn = null;
SqlCommand cmd = null;
using(conn = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString),
cmd = new SqlCommand(reportDataSource, conn)
{
conn = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString);
cmd = new SqlCommand(reportDataSource, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@Year", SqlDbType.Char, 4).Value = year;
cmd.Parameters.Add("@startDate", SqlDbType.DateTime).Value = start;
cmd.Parameters.Add("@endDate", SqlDbType.DateTime).Value = end;
cmd.Open();
DataSet dset = new DataSet();
new SqlDataAdapter(cmd).Fill(dset);
this.gridDataSource.DataSource = dset.Tables[0];
}
catch(Exception ex)
{
Logger.Log(ex);
throw;
}
using 语句只是创建一个 try/finally,并在finally 中调用 Dispose()。为什么不给开发人员一个统一的方式来进行处置和异常处理?