Does the using statement dispose only the first variable it create?

后端 未结 6 817
猫巷女王i
猫巷女王i 2021-01-12 15:27

Let\'s say I have a disposable object MyDisposable whom take as a constructor parameter another disposable object.

using(MyDisposable myDisposab         


        
6条回答
  •  星月不相逢
    2021-01-12 16:04

    In this case, it won't dispose the AnotherDisposable. There are two solutions to this.

    First, what you would normally do is the following:

    using (AnotherDisposable anotherDisposable = new AnotherDisposable())
    using (MyDisposable myDisposable= new MyDisposable(anotherDisposable))
    {
    }
    

    However, there is a different way to go. It's normal that when a class takes a disposable, it itself will take care of disposing the object it took. E.g. the StreamReader that wraps a Stream will dispose of the Stream it wraps. That means that the construct you choose would work. You can implement this same feature in MyDisposable and then the approach you took will be OK.

提交回复
热议问题