我喜欢这样使用它们:
static public void AddSampleData(String name)
{
String CreateScript = GetScript(String.Format("SampleData_{0}", name));
using (IDbConnection MyConnection = GetConnection())
{
MyConnection.Open();
IDbCommand MyCommand = MyConnection.CreateCommand();
foreach (String SqlScriptLine in CreateScript.Split(';'))
{
String CleanedString = SqlScriptLine.Replace(";", "").Trim();
if (CleanedString.Length == 0)
continue;
MyCommand.CommandText = CleanedString;
int Result = MyCommand.ExecuteNonQuery();
}
}
}
它们适用于您不想将错误检查代码仅清理并将错误传递下来的情况。替代方法如下所示:
static public void AddSampleData(String name)
{
String CreateScript = GetScript(String.Format("SampleData_{0}", name));
IDbConnection MyConnection = null;
try
{
IDbConnection MyConnection = GetConnection();
MyConnection.Open();
IDbCommand MyCommand = MyConnection.CreateCommand();
foreach (String SqlScriptLine in CreateScript.Split(';'))
{
String CleanedString = SqlScriptLine.Replace(";", "").Trim();
if (CleanedString.Length == 0)
continue;
MyCommand.CommandText = CleanedString;
int Result = MyCommand.ExecuteNonQuery();
}
}
finally
{
if (MyConnection != null
&& MyConnection.State == ConnectionState.Open)
MyConnection.Close();
}
}
坦率地说,哪种方法更容易阅读?与表格相同:
public void ChangeConfig()
{
using (ConfigForm MyForm = new ConfigForm())
{
DialogResult ConfigResult = MyForm.ShowDialog();
if (ConfigResult == DialogResult.OK)
SaveConfig();
}
ConfigForm MyForm = new ConfigForm();
DialogResult ConfigResult = MyForm.ShowDialog();
MyForm.Dispose();
if (ConfigResult == DialogResult.OK)
SaveConfig();
}