我应该如何正确地处理的对象? [英] How should I correctly dispose of an object?

查看:116
本文介绍了我应该如何正确地处理的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常使用下面的代码(或类似)处理的对象:

I frequently use the following code (or alike) to dispose of objects:

SqlCommand vCmd = null;

try 
{
    // CODE
}
catch(Exception ex) { /* EXCEPTION HANDLE */ }
finally 
{
    if (vCmd != null) 
    {
        vCmd.Dispose();
        vCmd = null;
    }
}

这是释放对象和处置的最佳途径对象?

Is this the best way to release objects and dispose of objects?

我使用的是VS的分析,给我一个关于裁员的警告。但是,我一直做这种方式...

I'm using the VS analytics and give me a warning about redundancies. But I always do it this way...

推荐答案

下面是从MSDN的例子:

Here is an example from MSDN:

private static void ReadOrderData(string connectionString)
{
    string queryString = 
        "SELECT OrderID, CustomerID FROM dbo.Orders;";
    using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        SqlCommand command = new SqlCommand(
            queryString, connection);
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        try
        {
            while (reader.Read())
            {
                Console.WriteLine(String.Format("{0}, {1}",
                    reader[0], reader[1]));
            }
        }
        finally
        {
            // Always call Close when done reading.
            reader.Close();
        }
    }
}

请注意使用使用为连接。

Note the use of "using" for the connection.

早在COM / ActiveX技术的昔日,你需要设置你的对象为无。

Back in the Olden Days of COM/ActiveX, you needed to set your objects to "Nothing".

在托管代码,这不再是必要的。

In managed code, this is no longer necessary.

您应该既不是所谓的处置(),也没有设置你的SqlCommand为空。

You should neither call "Dispose()", nor set your sqlCommand to "null".

刚刚停止使用 - 并信任的.Net垃圾收集器做休息

Just stop using it - and trust the .Net garbage collector to do the rest.

这篇关于我应该如何正确地处理的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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