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

后端 未结 6 920
猫巷女王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:09

    using is an equivalent of

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

    Thus, if myDisposable does not call Dispose on AnotherDisposable, using won't call it either.

提交回复
热议问题