using语句是否仅处理它创建的第一个变量? [英] Does the using statement dispose only the first variable it create?

查看:66
本文介绍了using语句是否仅处理它创建的第一个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个一次性对象MyDisposable,该对象将另一个一次性对象作为构造函数参数.

Let's say I have a disposable object MyDisposable whom take as a constructor parameter another disposable object.

using(MyDisposable myDisposable= new MyDisposable(new AnotherDisposable()))
{
     //whatever
}

假设myDisposable不在其dispose方法中处置AnotherDisposable.

Assuming myDisposable don't dispose the AnotherDisposable inside it's dispose method.

这仅正确处理myDisposable吗?还是也放置了AnotherDisposable?

Does this only dispose correctly myDisposable? or it dispose the AnotherDisposable too?

推荐答案

using等效于

MyDisposable myDisposable = new MyDisposable(new AnotherDisposable());
try
{
    //whatever
}
finally
{
    if (myDisposable != null)
        myDisposable.Dispose();
}

因此,如果myDisposable不调用AnotherDisposable上的Dispose,则using也不会调用它.

Thus, if myDisposable does not call Dispose on AnotherDisposable, using won't call it either.

这篇关于using语句是否仅处理它创建的第一个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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