如何为 SqlCommand 修复此 CA2000?

How to fix this CA2000 for SqlCommand?

我正在尝试执行如下所示的 SQL 查询,但 Visual Studio 抱怨 CA2000。

public static IDictionary<string, string> TemplateDirectories(string connectionString) {
    var directories = new Dictionary<string, string>();
    using (var connection = new SqlConnection(connectionString)) {
        connection.Open();
        using (var command = new SqlCommand { Connection = connection, CommandText = "select * from PATHS" }) {
            var reader = command.ExecuteReader();
            while (reader.Read())
                directories[reader["CODE"].ToString()] = reader["PATH"].ToString();
                reader.Close();
        }
    }
    return directories;
}

Error CA2000 ...object 'new SqlCommand()' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'new SqlCommand()' before all references to it are out of scope.

我尝试了多种方法来修复它,但没有一个奏效。那么如何解决呢?

尝试明确分配 command 参数:

using (var command = new SqlCommand())
{
    command.Connection = connection;
    command.CommandText="select * from PATHS";
    var reader = command.ExecuteReader();
    while (reader.Read())
        directories[reader["CODE"].ToString()] = reader["PATH"].ToString();
    reader.Close();
}

这是因为使用对象初始值设定项时的一个陷阱。

方法SqlCommand已经初始化,如果在初始化对象的过程中出现异常,SqlCommand将不会释放。

那么解决方法是什么。以老式方式声明对象,以消除警告-

using (var command = new SqlCommand())
{
    command.Connection = connection;
    command.CommandText="select * from PATHS";
    ...
}

我找到了一篇关于此的非常好的文章,其中提供了更多详细信息和解决问题的方法 - http://haacked.com/archive/2013/01/11/hidden-pitfalls-with-object-initializers.aspx/

话虽如此,对于这个特殊问题,最好使用 SqlCommand 的构造函数并像这样传递命令文本和连接对象(礼貌:Damien_The_Unbeliever的评论)

 string commandText = "select * from PATHS";
 using (var command = new SqlCommand(commandText, connection))
 {
  ...
 }