using语句是否只处理它创建的第一个变量?

Fab*_*ini 6 c# idisposable using

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

using(MyDisposable myDisposable= new MyDisposable(new AnotherDisposable()))
{
     //whatever
}
Run Code Online (Sandbox Code Playgroud)

假设myDisposable不处理它AnotherDisposable内部的处理方法.

这只能正确处理myDisposable吗?还是处理它AnotherDisposable

And*_*rei 9

using 相当于

MyDisposable myDisposable = new MyDisposable(new AnotherDisposable());
try
{
    //whatever
}
finally
{
    if (myDisposable != null)
        myDisposable.Dispose();
}
Run Code Online (Sandbox Code Playgroud)

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


sca*_*tag 5

为什么不嵌套它们?

using(var outer = new AnotherDisposable())
{
   using(var inner = new MyDisposable(outer))
   {
      //whatever
   }

}
Run Code Online (Sandbox Code Playgroud)

现在至少你可以确定它们会被正确处理掉.