Types that own disposable fields should be disposable. how to solve this warning?(拥有一次性字段的类型应该是一次性的.如何解决这个警告?)
问题描述
我尝试在 VisualStudio 2012 中使用 Run Code Analysis 选项,结果我收到了警告
I tried using Run Code Analysis option in VisualStudio 2012, as a result of it I got a warning as  
CA1001  Types that own disposable fields should be disposable
Implement IDisposable on 'DBConnectivity' 
because it creates members of the following IDisposable types: 'SqlConnection', 'SqlCommand'.
我在 SO 中提到了一些问题,但我无法理解关于 IDisposable 的重点以下是负责此警告的类.
I referred some question in SO, but I couldn't catch the point regarding IDisposable
and following is the class, responsible for this warning.
class DBConnectivity
    {
        public SqlConnection connection = null;
        public SqlCommand command = null;
        public SqlDataReader dataReader = null;
        public string connectionString = null;
        public List<MasterTableAttributes> masterTableList;
        public DBConnectivity()
        {
            connectionString = ConfigurationManager.ConnectionStrings["Master"].ConnectionString;
            connection = new SqlConnection(connectionString.ToString());
            //-----Master table results 
            connection.Open();
            string masterSelectQuery = "SELECT * FROM MASTER_TABLE";
            command = new SqlCommand(masterSelectQuery, connection);
            dataReader = command.ExecuteReader();
            masterTableList = new List<MasterTableAttributes>();
            while (dataReader.Read())
            {
                MasterTableAttributes masterTableAttribute = new MasterTableAttributes()
                {
                    fileId = Convert.ToInt32(dataReader["Id"]),
                    fileName = Convert.ToString(dataReader["FileName"]),
                    frequency = Convert.ToString(dataReader["Frequency"]),
                    scheduledTime = Convert.ToString(dataReader["Scheduled_Time"])
                };
                masterTableList.Add(masterTableAttribute);
            }
            dataReader.Close();
            connection.Close();
        }
    }
在实现 IDisposable 时我真的很困惑.任何帮助表示赞赏?
I am really confused in implementing the IDisposable. Any help appreciated?
推荐答案
我完全同意编译器 - 你需要在这里处理你的字段,或者(如前所述) - 首先不要让它们成为字段:
I fully agree with the compiler - you need to dispose your fields here, or (as already noted) - not make them fields in the first place:
class DBConnectivity : IDisposable // caveat! read below first
{
    public void Dispose() {
        if(connection != null) { connection.Dispose(); connection = null; }
        if(command != null) { command.Dispose(); command = null; }
        if(dataReader != null) { dataReader.Dispose(); dataReader = null; }
    }
请注意,然后您将通过 using(...)
Note that you would then use this type via using(...)
但是!看起来静态方法更合适:
However! It looks like a static method would be more appropriate:
static class DBConnectivity
{
    public static List<MasterTableAttributes> GetMasterTableList()
    {
        var connectionString = ConfigurationManager.ConnectionStrings["Master"].ConnectionString;
        using(var connection = new SqlConnection(connectionString))
        {
            connection.Open();
            const string masterSelectQuery = "SELECT * FROM MASTER_TABLE";
            using(var command = new SqlCommand(masterSelectQuery, connection))
            using(var dataReader = command.ExecuteReader())
            {
                var masterTableList = new List<MasterTableAttributes>();
                while (dataReader.Read())
                {
                    MasterTableAttributes masterTableAttribute = new MasterTableAttributes()
                    {
                        fileId = Convert.ToInt32(dataReader["Id"]),
                        fileName = Convert.ToString(dataReader["FileName"]),
                        frequency = Convert.ToString(dataReader["Frequency"]),
                        scheduledTime = Convert.ToString(dataReader["Scheduled_Time"])
                    };
                    masterTableList.Add(masterTableAttribute);
                }
                return masterTableList;
            }
        }
    }
}
或者使用dapper"之类的工具可能更简单:
or perhaps simpler with a tool like "dapper":
static class DBConnectivity
{
    public static List<MasterTableAttributes> GetMasterTableList()
    {
        var connectionString = ConfigurationManager.ConnectionStrings["Master"].ConnectionString;
        using(var connection = new SqlConnection(connectionString))
        {
            connection.Open();
            const string sql = "SELECT Id as [FileId], FileName, Frequency, Scheduled_Time as [ScheduledTime] FROM MASTER_TABLE";
            return connection.Query<MasterTableAttributes>(sql).ToList();
        }
    }
}
                        这篇关于拥有一次性字段的类型应该是一次性的.如何解决这个警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:拥有一次性字段的类型应该是一次性的.如何解决这个警告?
				
        
 
            
        - C# 中多线程网络服务器的模式 2022-01-01
 - 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
 - 如何用自己压缩一个 IEnumerable 2022-01-01
 - 输入按键事件处理程序 2022-01-01
 - 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
 - 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
 - WebMatrix WebSecurity PasswordSalt 2022-01-01
 - C#MongoDB使用Builders查找派生对象 2022-09-04
 - MoreLinq maxBy vs LINQ max + where 2022-01-01
 - Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
 
						
						
						
						
						
				
				
				
				