returning in the middle of a using block

后端 未结 7 1087
一生所求
一生所求 2020-11-27 15:08

Something like:

using (IDisposable disposable = GetSomeDisposable())
{
    //.....
    //......
    return Stg();
}

I believe it is not a p

7条回答
  •  Happy的楠姐
    2020-11-27 15:22

    The code bellow shows how using is working:

    private class TestClass : IDisposable
    {
       private readonly string id;
    
       public TestClass(string id)
       {
          Console.WriteLine("'{0}' is created.", id);
          this.id = id;
       }
    
       public void Dispose()
       {
          Console.WriteLine("'{0}' is disposed.", id);
       }
    
       public override string ToString()
       {
          return id;
       }
    }
    
    private static TestClass TestUsingClose()
    {
       using (var t1 = new TestClass("t1"))
       {
          using (var t2 = new TestClass("t2"))
          {
             using (var t3 = new TestClass("t3"))
             {
                return new TestClass(String.Format("Created from {0}, {1}, {2}", t1, t2, t3));
             }
          }
       }
    }
    
    [TestMethod]
    public void Test()
    {
       Assert.AreEqual("Created from t1, t2, t3", TestUsingClose().ToString());
    }
    

    Output:

    't1' is created.
    't2' is created.
    't3' is created.
    'Created from t1, t2, t3' is created.
    't3' is disposed.
    't2' is disposed.
    't1' is disposed.

    The disposed are called after the return statement but before the exit of the function.

提交回复
热议问题