C# using statement catch error

后端 未结 16 1465
轻奢々
轻奢々 2021-01-30 14:06

I am just looking at the using statement, I have always known what it does but until now not tried using it, I have come up with the below code:

 using (SqlComma         


        
16条回答
  •  悲&欢浪女
    2021-01-30 14:35

    There are a lot of great answers here, but I don't think this has been said yet.

    No matter what... the "Dispose" method WILL be called on the object in the "using" block. If you put a return statement, or throw an error, the "Dispose" will be called.

    Example:

    I made a class called "MyDisposable", and it implements IDisposable and simply does a Console.Write. It always writes to the console even in all these scenarios:

    using (MyDisposable blah = new MyDisposable())
    {
        int.Parse("!"); // <- calls "Dispose" after the error.
    
        return; // <-- calls Dispose before returning.
    }
    

提交回复
热议问题