在我维护的一些代码中,我遇到了这个:
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
没有执行(除非引发异常)?或者这是完全没用的代码吗?
答案 0 :(得分:4)
那段代码没用......
如果你添加一个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
}
答案 1 :(得分:2)
根据using Statement documentation,您可以将代码翻译为
int flag;
{
StreamReader reader = new StreamReader(FileName, Encoding.GetEncoding("iso-8859-1"), true);
try
{
flag = 1;
// Some computing code
}
finally
{
if (reader != null) ((IDisposable)reader).Dispose();
}
}
if (flag == 1)
{
// Some other code
}
如果您达到flag == 1
测试,则表示您的代码没有被抛出,因此,标记设置为1
。所以,是的,flag
东西在你的情况下是完全没用的代码。
答案 2 :(得分:0)
代码总是在using语句中执行,除非实例的创建引发异常。
考虑到这一点。
int Flag;
using (StreamReader reader = new StreamReader(FileName, Encoding.GetEncoding("iso-8859-1"), true))
{
// This scope is executed if the StreamReader instance was created
// If ex. it can't open the file etc. then the scope is not executed
Flag = 1;
}
// Does not run any code past this comment
// if the using statement was not successfully executed
// or there was an exception thrown within the using scope
if(Flag == 1)
{
// Some other code
}
但是,有一种方法可以确保执行代码的下一部分。 使用try语句可以确保设置标志。 这可能不是您想要做的,但根据您的代码,它将确保设置标志。也许你还需要其他一些逻辑。
int Flag;
try
{
using (StreamReader reader = new StreamReader(FileName, Encoding.GetEncoding("iso-8859-1"), true))
{
// This scope is executed if the StreamReader instance was created
// If ex. it can't open the file etc. then the scope is not executed
Flag = 1;
}
}
catch (Exception e)
{
// Do stuff with the exception
Flag = -1; // Error Flag perhaps ??
}
// Any code after this is still executed
if(Flag == 1)
{
// Some other code
}