在我维护的一些代码中,我遇到了这个:
int Flag;
using (StreamReader reader = new StreamReader(FileName, Encoding.GetEncoding("iso-8859-1"), true))
{
Flag = 1;
// Some computing code
}
if(Flag == 1)
{
// Some other code
}
据我所知,如果执行了 using
部分,这是一种执行其他指令的方法。但是是否有可能 using
不被执行(除非引发异常)?或者这是完全无用的代码?
最佳答案
那个代码没用...
如果您添加一个 try
... catch
它可能有一种意义...您想知道是否/在哪里发生异常,例如:
int flag = 0;
try
{
using (StreamReader reader = new StreamReader(FileName, Encoding.GetEncoding("iso-8859-1"), true))
{
flag = 1;
reader.ReadToEnd();
flag = 2;
}
flag = int.MaxValue;
}
catch (Exception ex)
{
}
if (flag == 0)
{
// Exception on opening
}
else if (flag == 1)
{
// Exception on reading
}
else if (flag == 2)
{
// Exception on closing
}
else if (flag == int.MaxValue)
{
// Everything OK
}
关于c# - using var 总是被执行吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31587322/