首页 > 解决方案 > Visual Studio 推荐使用命令简化

问题描述

自从更新 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#visual-studiousingc#-8.0

解决方案


这称为使用声明。

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

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

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


推荐阅读