假设我有一个一次性对象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/