【发布时间】:2019-10-29 14:16:35
【问题描述】:
自从更新 Visual Studio 以来,我注意到它现在建议使用语句来简化我的 MySQL。
它想改变这个:
using (MySqlCommand command = new MySqlCommand(sql_string, connection))
{
command.Parameters.AddWithValue("@id", id);
MySqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
business = new Business()
{
Id = int.Parse(reader["id"].ToString()),
Name = reader["name"].ToString(),
};
reader.Dispose();
}
}
进入这个:
using MySqlCommand command = new MySqlCommand(sql_string, connection);
command.Parameters.AddWithValue("@id", id);
MySqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
business = new Business()
{
Id = int.Parse(reader["id"].ToString()),
Name = reader["name"].ToString(),
};
reader.Dispose();
}
我的问题是,以前代码会像这样用括号括起来:
using (MySqlCommand command = new MySqlCommand(sql_string, connection))
{
}
IntelliSense 推荐的建议是否有效且不会导致任何泄漏?
【问题讨论】:
-
这是一种使用 c#8 (vs 2019) 中可用的块声明的新方法docs.microsoft.com/en-us/dotnet/csharp/whats-new/…
-
正确,读者也需要包装。
-
如果我要处理它,阅读器是否需要包装?
-
@ScottC 如果在您处置之前发生异常,那么您不会处置,因为您没有在 try/finally 的 finally 块中使用处置。或者如果它的
HasRows属性为假。 -
您应该将您的阅读器声明为
using MySqlDataReader reader = command.ExecuteReader();,以确保它也始终被释放(并删除对reader.Dispose();的显式调用
标签: c# visual-studio using c#-8.0