代码分析警告 CA2213 - 在 IDisposable 支持字段上调用 ​​Dispose()

Code Analysis Warning CA2213 - Call Dispose() on IDisposable backing field

想要post这个,即使我在写问题的时候想出来了。请post在下面回答。

使用 VS 代码分析得到以下警告:

Warning CA2213 'DBConn' contains field 'DBConn.k__BackingField' that is of IDisposable type: 'SqlConnection'. Change the Dispose method on 'DBConn' to call Dispose or Close on this field.

但是我的代码 确实 调用了 DBConn 属性 上的 Dispose()。它不在后台吗?我还有其他类似的实例 - 我正在处理编译器不会抛出此警告的地方。这是下面的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;    

namespace TheProgramSpace
{
    public sealed class DBConn : IDisposable
    {
        // class containing the database and its connection
        public SqlConnection TheConn { get; }
        public string DbPath { get; }
        public string DbName { get; }


        public DBConn(ProgInstance FPI)
        {
            // constructs new SQLConnection            
            DbPath = FPI.dbPath;
            DbName = FPI.dbName;

            string connString = "Data Source = " + DbPath + "; Initial Catalog =" + DbName + "; Integrated Security = True; "
              + "Connect Timeout = 30; Encrypt = False; TrustServerCertificate = False; "
              + "ApplicationIntent = ReadWrite; MultiSubnetFailover = False";                     

            TheConn = new SqlConnection(connString);

        }

        public void Dispose()
        {            
            TheConn.Dispose();            
        }
    }
}

原因是 TheConn,因为它没有 set 访问器,所以是 read-only。将 属性 声明更改为

public SqlConnection TheConn { get; private set; }

解决了问题。

您的代码没有问题。 Dispose 在基础支持字段上调用。这是一个 known bug in FxCop that surfaced with the introduction of "getter-only" automatic properties which were introduced in C# 6. For now, you can either suppress the warning,在 class 上有一个属性,或者忽略它,直到它在 FxCop 中得到修复。