拥有一次性字段的类型应该是一次性的.如何解决这个警告? [英] Types that own disposable fields should be disposable. how to solve this warning?

查看:23
本文介绍了拥有一次性字段的类型应该是一次性的.如何解决这个警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在 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();
        }
    }
}

这篇关于拥有一次性字段的类型应该是一次性的.如何解决这个警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆