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

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

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

这只会正确处理myDisposable吗?还是也处理了AnotherDisposable

最佳答案

using等效于

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

因此,如果myDisposable没有在AnotherDisposable上调用Dispose,那么using也不会调用它。

关于c# - using语句是否仅处理它创建的第一个变量?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17317251/

10-09 04:34