7

今天有一个精神障碍,需要一只手来验证我的逻辑没有被fubar'ed。

传统上我会做类似这样的文件 i/o:

FileStream fs = null; // So it's visible in the finally block
try
{
   fs = File.Open("Foo.txt", FileMode.Open);

   /// Do Stuff
}
catch(IOException)
{
   /// Handle Stuff
}
finally
{
   if (fs != null)
      fs.Close();
}

但是,这不是很优雅。

理想情况下,我想在完成后使用该using块来处理文件流,但是我不确定 using 和 try/catch 之间的协同作用。

这就是我想实现上述内容的方式:

try
{
   using(FileStream fs = File.Open("Foo.txt", FileMode.Open))
   {
      /// Do Stuff
   }
}
catch(Exception)
{
   /// Handle Stuff
}

但是,我担心 using 块中的过早退出(通过抛出的异常)可能不允许 using 块完成执行并清理它的对象。我只是偏执狂,还是这实际上会按照我的意图进行?

4

6 回答 6

17

你只是偏执它会按照你想要的方式工作:)

using 语句等同于 try/finally 块,无论它是否在 try/catch 中。

所以你的代码类似于:

try
{
   FileStream fs = null;
   try
   {
       fs = File.Open("Foo.txt", FileMode.Open);
       // Do stuff
   }
   finally
   {
       if (fs != null)
       {
           fs.Dispose();
       }
   }
}
catch(Exception)
{
   /// Handle Stuff
}
于 2010-04-28T18:14:54.470 回答
0

不用担心,它会按预期清理,并且比原来的更干净。

事实上,在业务逻辑中使用 try/finally aka using 语句以及在 UI 层或物理层边界的顶级处理程序中使用 try/catch 更为常见。就像是:

try
{
    DoStuffWithFile("foo.txt");
}
catch(Exception ex)
{
   ...
}

public void DoStuffWithFile(string fileName)
{
    using(FileStream fs = File.Open(fileName,...))
    {
        // Do Stuff
    }
}
于 2010-04-28T18:15:02.443 回答
0

这将起作用 - 在内部 using 语句的编译方式与 try-finally 块相同

于 2010-04-28T18:15:40.193 回答
0
    try
    {
        FileStream fs = null;
        try
        {
           fs = File.Open("Foo.txt", FileMode.Open);

        }
        finally
        {
           fs.Dispose();
        }
    }
    catch(Exception)
    {
       /// Handle Stuff
    }

第二段代码被翻译成这个

于 2010-04-28T18:15:55.647 回答
0

using 块将完全按照您的意图翻译 using 块实际上只是

try
{
   FileStream fs = null;
   try
   {
        fs = File.Open("Foo.txt", FileMode.Open))
        //Do Stuff
   }
   finally
   {
      if(fs != null)
          fs.Dispose();
   }
}
catch(Exception)
{
   /// Handle Stuff
}
于 2010-04-28T18:16:20.983 回答
0

如果您try..finallyusing(). 它们执行相同的操作。

如果您不相信,请将Reflector指向您的程序集并比较生成的代码。

于 2010-04-28T18:16:33.017 回答