Visual Studio建议简化使用命令 [英] Visual Studio Recommending to Simplify Using Command

查看:71
本文介绍了Visual Studio建议简化使用命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自从更新Visual Studio以来,我已经注意到现在建议使用语句简化我的MySQL.

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

它想要更改此:

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

我的问题是,以前的代码会像这样用括号括起来:

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

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

            }

IntelliSense推荐的建议是否有效并且不会引起任何泄漏?

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

推荐答案

这称为使用声明".

using声明是一个变量声明,其后是using关键字.它告诉编译器应将声明的变量放在封闭范围的末尾.

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.

只要您需要在编译器建议的相同作用域内使用using变量,就不成问题.

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

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

这篇关于Visual Studio建议简化使用命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆