简体   繁体   English

为什么我们在 c# 中使用嵌套的 using 语句?

[英]why we use nested using statement in c#?

using (StreamReader outFile = new StreamReader(outputFile.OpenRead())) 
{    
   StreamReader resFile = new StreamReader(resultFile.OpenRead())    
   {       //Some Codes    }
}

Why does the above resFile object not close automatically?为什么上面的resFile object没有自动关闭?

I wrote the resFile object inside the using statement also.我也在 using 语句中写了 resFile object 。 Please explain the using statement.请解释using语句。

You didn't use nested using.你没有使用嵌套使用。 There's only one using statement.只有一个 using 语句。

An example of nested using:嵌套使用示例:

using (...)
{
     using (...)
     {
         ...
     }
}

The reason why you may want to use nested using is that you have more than one declaration that need to be disposed.您可能想要使用嵌套使用的原因是您有多个声明需要处理。

Find the official explanation for the using statement here: https://learn.microsoft.com/en-us/do.net/csharp/language-reference/keywords/using-statement在这里找到 using 语句的官方解释: https://learn.microsoft.com/en-us/do.net/csharp/language-reference/keywords/using-statement

In your example you are not having a nested using statement as Mark said correctly in his answer.在您的示例中,您没有嵌套的 using 语句,正如 Mark 在他的回答中正确所说的那样。 (Though you should have a second using for the resFile Streamreader. (尽管您应该第二次使用 resFile Streamreader。

They have to be nested, if you want to use both stream readers in the "// Some Codes" part, as the instances for outFile and resFile are only available inside the curly brackets.如果您想在“// Some Codes”部分同时使用 stream 阅读器,它们必须嵌套,因为 outFile 和 resFile 的实例仅在大括号内可用。

Starting from C#8 there is a new possibility for usings that "avoids" the nesting.从 C#8 开始,可以使用“避免”嵌套的新方法。 See: https://learn.microsoft.com/de-de/do.net/csharp/language-reference/proposals/csharp-8.0/using参见: https://learn.microsoft.com/de-de/do.net/csharp/language-reference/proposals/csharp-8.0/using

using is syntactic sugar and basically compiles to the following: using是语法糖,基本上可以编译成以下内容:

Original code:原始代码:

using (var a = b)
{    
  c();
  d();
}

Desugared code:脱糖代码:

{
  var a;
  try {
    a = b;
    c();
    d();
  } finally {
    if (a != null) {
      ((IDisposable)a).Dispose();
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM