Visual Studio Recommending to Simplify Using Command

半腔热情 提交于 2021-02-04 21:19:13

问题


I've noticed since updating Visual Studio that it is now recommending to simplify my MySQL using statements.

It wants to change this:

            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();
                }
            }

Into this:

            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();
            }

My question is, previously the code would be wrapped in brackets like so:

            using (MySqlCommand command = new MySqlCommand(sql_string, connection))
            {

            }

Is the recommended suggestion by IntelliSense valid and won't cause any leaks?


回答1:


This is called a Using Declaration.

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.

As long as you need the using variable in the same scope suggested by the compiler, it should not be a problem.

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



来源:https://stackoverflow.com/questions/58609253/visual-studio-recommending-to-simplify-using-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!