一次性用品、使用和使用尝试/捕获块
今天有精神障碍,需要有人来验证我的逻辑是否混乱。
传统上我会执行与此类似的文件 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 块完成执行并清理其对象。我只是偏执吗,还是这实际上会按照我的预期进行?
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; // 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();
}
However, this isn't very elegant.
Ideally I'd like to use the using
block to dispose of the filestream when I'm done, however I am unsure about the synergy between using and try/catch.
This is how i'd like to implement the above:
try
{
using(FileStream fs = File.Open("Foo.txt", FileMode.Open))
{
/// Do Stuff
}
}
catch(Exception)
{
/// Handle Stuff
}
However, I'm worried that a premature exit (via thrown exception) from within the using block may not allow the using block to complete execution and clean up it's object. Am I just paranoid, or will this actually work the way I intend it to?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
你只是偏执和它会按照你想要的方式工作:)
using 语句相当于一个 try/finally 块,无论它是否在 try/catch 中。
所以你的代码类似于:
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/finally 又名 using 语句,以及在 UI 层或物理层边界的顶级处理程序中使用 try/catch 更为常见。像这样的东西:
和
Don't worry, it will clean up as expected and is cleaner than your original.
In fact it's much more common to have a try/finally aka using statement in your business logic, and a try/catch in a top-level handler in the UI tier or at a physical tier boundary. Something like:
and
这将起作用 - 在内部 using 语句的编译方式与 try-finally 块相同
This will work - internally the using statement compiles the same way as a try-finally block
第二段代码被翻译成这样
second piece of code gets translated into this
using 块将完全按照您想要的方式工作,翻译 using 块实际上只是
The using block will work exactly as you entend translated the using block is really just
如果您有
using()
,则不需要try..finally
。他们执行相同的操作。如果您不相信,请将 Reflector 指向您的程序集并比较生成的代码。
You don't need the
try..finally
if you have ausing()
. They perform the same operation.If you're not convinced, point Reflector at your assembly and compare the generated code.