代码分析警告 CA2213 - 在 IDisposable 支持字段上调用 Dispose() [英] Code Analysis Warning CA2213 - Call Dispose() on IDisposable backing field
问题描述
想发布这个,即使我在写问题的时候就想通了.将在下面发布答案.
Wanted to post this, even though I figured it out as I was writing the question. Will post answer below.
使用 VS Code 分析得到以下警告:
Getting the following warning with VS Code Analysis:
警告 CA2213DBConn"包含 IDisposable 类型的字段DBConn.k__BackingField":SqlConnection".将DBConn"上的 Dispose 方法更改为对该字段调用 Dispose 或 Close.
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().不是在后台吗?我还有其他类似的实例 - 我正在处理编译器没有抛出此警告的地方.这是下面的代码:
But my code does call Dispose() on the DBConn property. Does it not on the backing field? I have other instances like this - where I am disposing of where the compiler does not throw this warning. This is the code below:
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();
}
}
}
推荐答案
您的代码没有问题.Dispose
将 在底层支持字段上调用.这是 FxCop 中的一个已知错误,随着getter-only"自动的引入而浮出水面在 C# 6 中引入的属性.现在,您可以抑制警告 在类上带有属性,或者只是忽略它,直到它在 FxCop 中得到修复.
There is not a problem with your code. Dispose
will be called on the underlying backing field. This is a 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 with an attribute on the class or just ignore it until it's fixed in FxCop.
这篇关于代码分析警告 CA2213 - 在 IDisposable 支持字段上调用 Dispose()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!