using var总是执行吗

本文关键字:执行 var using | 更新日期: 2023-09-27 18:04:09

在我维护的一些代码中,我遇到了以下内容:

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(除非引发异常(?或者这是完全无用的代码?

using var总是执行吗

那个代码没用。。。

如果添加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
}

基于使用Statement文档,您可以将代码转换为

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的东西在您的情况下是完全无用的代码。

除非实例的创建引发异常,否则代码始终在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
}