Disposables, Using & Try/Catch Blocks

后端 未结 6 1404
一向
一向 2020-12-19 05:56

Having a mental block today, need a hand verifying my logic isn\'t fubar\'ed.

Traditionally I would do file i/o similar to this:

FileStream fs = null         


        
6条回答
  •  情书的邮戳
    2020-12-19 06:27

    You're just being paranoid and it will work the way you intend it to :)

    A using statement is equivalent to a try/finally block, whether it's inside a try/catch or not.

    So your code is similar to:

    try
    {
       FileStream fs = null;
       try
       {
           fs = File.Open("Foo.txt", FileMode.Open);
           // Do stuff
       }
       finally
       {
           if (fs != null)
           {
               fs.Dispose();
           }
       }
    }
    catch(Exception)
    {
       /// Handle Stuff
    }
    

提交回复
热议问题