【发布时间】:2023-04-11 17:07:02
【问题描述】:
想发布这个,即使我在写问题时想通了。将在下面发布答案。
使用 VS 代码分析得到以下警告:
警告 CA2213“DBConn”包含 IDisposable 类型的字段“DBConn.k__BackingField”:“SqlConnection”。将“DBConn”上的 Dispose 方法更改为在该字段上调用 Dispose 或 Close。
但我的代码确实在 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();
}
}
}
【问题讨论】:
-
您使用的是什么版本的 C#?在 C# 6 之前,您会收到 不同的 编译器警告,因为您必须为自动属性提供设置器。
-
这是 FxCop 中的 known bug,将在未来的版本中修复。
标签: c# visual-studio visual-studio-2015 fxcop c#-6.0