是一个使用块内的所有实例化对象一次性处置? [英] Are all disposable objects instantiated within a using block disposed?

查看:199
本文介绍了是一个使用块内的所有实例化对象一次性处置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我问自己很多次,在过去,因为我嵌套using语句5深的问题。



阅读文档和发现。没有提到关于任何一种方式的其他的我觉得是这么档案的好Q上的块中实例化的耗材



考虑一下:

 使用(VAR康恩=新的SqlConnection())
{
变种CONN2 =新的SqlConnection();
}

//配置CONN2?


解决方案

很显然,我有答案... ;-)



答案是否定的。只有在使用申报的物品设置

  [测试] 
公共无效TestUsing()
{
布尔innerDisposed = FALSE;
使用(VAR康恩=新的SqlConnection())
{
变种CONN2 =新的SqlConnection();
conn2.Disposed + =(发件人,E)=> {innerDisposed = TRUE; };
}

Assert.False(innerDisposed); //未布置
}

[测试]
公共无效TestUsing2()
{
布尔innerDisposed = FALSE;
使用(SqlConnection的康恩=新的SqlConnection(),CONN2 =新的SqlConnection())
{
conn2.Disposed + =(发件人,E)=> {innerDisposed = TRUE; };
}
Assert.True(innerDisposed); //处理过程
}


的,

This is a question I have asked myself many times in the past as I nested using statements 5 deep.

Reading the docs and finding no mention either way regarding other disposables instantiated within the block I decided it was a good Q for SO archives.

Consider this:

using (var conn = new SqlConnection())
{
    var conn2 = new SqlConnection();
}

// is conn2 disposed?

解决方案

Obviously I have the answer... ;-)

The answer is no. Only the objects in the using declaration are disposed

[Test]
public void TestUsing()
{
    bool innerDisposed = false;
    using (var conn = new SqlConnection())
    {
        var conn2 = new SqlConnection();
        conn2.Disposed += (sender, e) => { innerDisposed = true; };
    }

    Assert.False(innerDisposed); // not disposed
}

[Test]
public void TestUsing2()
{
    bool innerDisposed = false;
    using (SqlConnection conn = new SqlConnection(), conn2 = new SqlConnection())
    {
        conn2.Disposed += (sender, e) => { innerDisposed = true; };
    }
    Assert.True(innerDisposed); // disposed, of course
}

这篇关于是一个使用块内的所有实例化对象一次性处置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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