今天有一个心理障碍,需要帮忙验证我的逻辑是不fubar'ed。
Having a mental block today, need a hand verifying my logic isn't fubar'ed.
传统上我会做的文件I / O与此类似:
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.
在理想情况下,我想使用使用
块处分时,我做的文件流的,但是我不能确定如何使用和try / catch之间的协同作用
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
}
不过,我担心使用块中的premature出口(通过抛出异常)可能不允许使用块来完成执行和清理它的对象。我只是偏执,或将在实际工作我想让它的方式吗?
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?
你只是被偏执的和的它会工作的方式,你想让它:)
You're just being paranoid and it will work the way you intend it to :)
using语句相当于一个try / finally块,无论是在try / catch里面还是不行。
A using statement is equivalent to a try/finally block, whether it's inside a try/catch or not.
所以,你的code是类似于:
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
}