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

后端 未结 6 816
猫巷女王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 15:53

    C#’s using statement provides a syntactic shortcut for calling Dispose on objects that implement IDisposable, using a try/finally block. For example:

    using (FileStream fs = new FileStream ("myFile.txt", FileMode.Open))
    {
    // ... Write to the file ...
    }
    

    The compiler converts this to: FileStream fs = new FileStream ("myFile.txt", FileMode.Open);

    try
    {
    // ... Write to the file ...
    }
    finally
    {
    if (fs != null) ((IDisposable)fs).Dispose();
    }
    

    The finally block ensures that the Dispose method is called even when an exception is thrown,1 or the code exits the block early.

    So for using single block will only ensure that the single disposable object will be disposed. on the other hand you can use a nested using statements. like

    using (myDisposable d = new myDisposable())
    {
      using(Disposable2 d2 = new Disposable2())
      {
    // do something and dispose...
      }
    }
    

    and this will be converted as

    try
    {
      // work around for myDisposable  
    
        try
         {
          // work around for Disposable2 
         }
        finally
        {
        if (d2 != null) 
             ((IDisposable)d2 ).Dispose();
        }    
    }
    finally
    {
         if (d!= null)
              ((IDisposable)d).Dispose();
    }
    

提交回复
热议问题