会“使用"吗?还处理在构造函数中创建的对象? [英] Does "using" also dispose objects created in the constructor?
问题描述
在创建实现 IDisposable
的元素时,如果抛出异常,也会在 using
块的末尾调用 Dispose()
,如果我是正确的话.
When creating an element that implements IDisposable
, Dispose()
is called at the end of the using
block also if an exception is thrown, if I'm correct.
但是,当在一次性元素的构造函数中创建 ClassB
的新元素时,如果实现了 IDisposable
,是否也会处理ClassB的对象?
However, when creating a new element of ClassB
within the constructor of a disposable element, will the object of ClassB also be disposed if IDisposable
is implemented?
using (ClassA a = new ClassA(new ClassB()))
{
}
这可能适用于与 Stream
相关的类.但是,这通常适用吗?
This may apply to classes that are related to Stream
. However, does this apply in general?
推荐答案
ClassB
仅在 ClassA
调用的dispose方法被处理时丢弃在上面.
ClassB
would only be disposed if the dispose method of ClassA
calls dispose on it.
class ClassA : IDisposable
{
private ClassB b;
public ClassA (ClassB b) { this.b = b; }
public void Dispose() { this.b.Dispose(); }
}
如果没有,则需要单独处理:
If it doesn't you'll need to dispose of it separately:
using (ClassB b = new ClassB())
using (ClassA a = new ClassA(b))
{
}
这篇关于会“使用"吗?还处理在构造函数中创建的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!