C# VisualStudio建议简化命令的使用
我注意到,自从更新VisualStudio之后,它现在建议使用语句简化我的MySQL 它想改变这一点:C# VisualStudio建议简化命令的使用,c#,visual-studio,using,c#-8.0,C#,Visual Studio,Using,C# 8.0,我注意到,自从更新VisualStudio之后,它现在建议使用语句简化我的MySQL 它想改变这一点: using (MySqlCommand command = new MySqlCommand(sql_string, connection)) { command.Parameters.AddWithValue("@id", id); MySqlDataReader reader
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的建议是否有效且不会导致任何泄漏?这称为使用声明 using声明是一个变量声明,前面有using关键字。它告诉编译器要声明的变量应该在封闭范围的末尾处理 只要您需要在编译器建议的相同范围内使用变量,就不会有问题
参考:这称为使用声明 using声明是一个变量声明,前面有using关键字。它告诉编译器要声明的变量应该在封闭范围的末尾处理 只要您需要在编译器建议的相同范围内使用变量,就不会有问题
参考资料:这是一种新的方法来声明使用c#8(vs 2019)中可用的块是正确的,读卡器也需要包装。如果我要处理它,读卡器是否需要包装?@ScottC如果在处理之前发生异常,则您不处理,因为您没有在try/finally的finally块中使用dispose。或者如果其
HasRows
属性为false,则应使用MySqlDataReader reader=command.ExecuteReader()将读取器声明为
以确保它也总是被释放(并删除对reader.Dispose();
的显式调用这是一种使用c#8(vs 2019)中可用的块声明的新方法它是正确的,读卡器也需要包装。如果我要处理它,读卡器需要包装吗?@ScottC如果在处理之前发生异常,那么您不处理,因为您没有在try/finally的finally块中使用dispose。或者如果它的HasRows
属性为false。您应该使用MySqlDat将读卡器声明为aReader reader=command.ExecuteReader();
以确保它也始终被释放(并删除对reader.Dispose()的显式调用;