Does “using” also dispose objects created in the constructor? [duplicate]

℡╲_俬逩灬. 提交于 2021-01-29 05:23:59

问题


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.

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()))
{
}

This may apply to classes that are related to Stream. However, does this apply in general?


回答1:


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))
{
}



回答2:


Short answer, no. If ClassB implements IDisposable, you should wrap it in a using block too:

using (var b = new ClassB())
using (var a = new ClassA(b))
{
    // do stuff
}

Keep in mind that everything you pass to a constructor, or any other method which accepts parameters is evaluated before the constructor or method is invoked.

Some classes, like StreamWriter does with a Stream, will dispose whatever is passed through the constructor, but it's common to leave the disposing to whoever actually instantiated the object.



来源:https://stackoverflow.com/questions/37836565/does-using-also-dispose-objects-created-in-the-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!