【问题标题】:Visual Studio Recommending to Simplify Using CommandVisual Studio 推荐使用命令简化
【发布时间】: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


【解决方案1】:

这称为使用声明。

using 声明是一个以 using 关键字开头的变量声明。它告诉编译器被声明的变量应该被放置在封闭范围的末尾。

只要你需要在编译器建议的相同范围内的 using 变量,它应该不是问题。

参考:https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#using-declarations

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-23
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2011-09-21
    • 2021-12-20
    相关资源
    最近更新 更多