Visual Studio 推荐使用命令简化

Visual Studio Recommending to Simplify Using Command

自更新 Visual Studio 以来,我注意到它现在建议简化我的 MySQL using 语句。

它想改变这个:

            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 推荐的建议是否有效,不会造成任何泄漏?

这称为使用声明。

A using declaration is a variable declaration preceded by the using keyword. It tells the compiler that the variable being declared should be disposed at the end of the enclosing scope.

只要你需要在编译器建议的相同范围内使用变量,应该没有问题。

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