利用处置嵌套对象的使用嵌套、对象

2023-09-03 17:25:53 作者:都滚,我是屌丝

如果我有code像这样的嵌套对象是否需要使用using语句,以确保双方的SqlCommand和的SQLConnection对象妥善处理嵌套像图所示还是我确定,如果在code实例化SqlCommand的是使用的语句外之内。

 使用(VAR康恩=新的SqlConnection(sqlConnString))
{
    使用(VAR CMD =新的SqlCommand())
    {
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = cmdTextHere;
        conn.Open();

        cmd.Connection =康涅狄格州;
        的RowsAffected = cmd.ExecuteNonQuery();
    }
}
 

解决方案

是的。你可以清理有点像这样

 使用(SqlConnection的康恩=新的SqlConnection(sqlConnString))
使用(System.Data.SqlClient.SqlCommand CMD =新System.Data.SqlClient.SqlCommand())
{
   // code在这里
}
 
数据挖掘 模型构建及预测

但是,你仍然想有一个使用每个IDisposable的对象。

编辑:考虑一下这个例子中的没有的使用内部使用语句

  A级:IDisposable的
{
    公共无效的Dispose()
    {
        Console.WriteLine(已释放);
    }
}

B类:IDisposable的
{
    公共无效的Dispose()
    {
        Console.WriteLine(乙处置);
    }
}
 

code

 用(A =一个新的A())
{
    B B =新的B();
}
 

在块结束时,妥善处理。会发生什么到B?嗯,这是超出范围,只是在等待被垃圾收集。 B.Dispose()将不会调用。另一方面

 用(A =一个新的A())
用(B B =新的B())
{
}
 

在执行离开块(实际上,块的),编译code执行调用每个对象的Dispose()方法。

If I have code with nested objects like this do I need to use the nested using statements to make sure that both the SQLCommand and the SQLConnection objects are disposed of properly like shown below or am I ok if the code that instantiates the SQLCommand is within the outer using statement.

using (var conn = new SqlConnection(sqlConnString))
{
    using (var cmd = new SqlCommand())
    {
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = cmdTextHere;
        conn.Open();

        cmd.Connection = conn;
        rowsAffected = cmd.ExecuteNonQuery();
    }
}

解决方案

Yes. You could clean it up a little like this

using (SqlConnection conn = new SqlConnection(sqlConnString))
using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand())
{
   // code here
}

But you would still want a using for each IDisposable object.

Edit: Consider this example of not using an inner using statement.

class A : IDisposable
{
    public void Dispose()
    {
        Console.WriteLine("A Disposed");
    }
}

class B : IDisposable
{
    public void Dispose()
    {
        Console.WriteLine("B Disposed");
    }
}

Code

using (A a = new A())            
{
    B b = new B();
}

At the end of the block, A is properly disposed. What happens to B? Well, it's out of scope and simply waiting to be garbage collected. B.Dispose() is not called. On the other hand

using (A a = new A())
using (B b = new B())
{
}

When execution leaves the block (actually, blocks), the compiled code executes calls to the Dispose() method of each object.