【问题标题】:why we use nested using statement in c#?为什么我们在 C# 中使用嵌套的 using 语句?
【发布时间】:2022-12-12 14:56:44
【问题描述】:
`using (StreamReader outFile = new StreamReader(outputFile.OpenRead())) 
 {    
   StreamReader resFile = new StreamReader(resultFile.OpenRead())    
   {       //Some Codes    }
 }`

为什么上面的 resFile 对象不会自动关闭。

我也在 using 语句中写了 resFile 对象。请解释使用声明。

【问题讨论】:

    标签: c# using using-statement


    【解决方案1】:

    你没有使用嵌套使用。只有一个 using 语句。

    嵌套使用示例:

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

    您可能想要使用嵌套使用的原因是您有多个声明需要处理。

    【讨论】:

      【解决方案2】:

      在这里找到 using 语句的官方解释: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement

      在您的示例中,您没有嵌套的 using 语句,正如 Mark 在他的回答中正确所说的那样。 (尽管您应该第二次使用 resFile Streamreader。

      它们必须是嵌套的,如果你想在“// Some Codes”部分使用两个流阅读器,因为 outFile 和 resFile 的实例只在大括号内可用。

      从 C#8 开始,就有了新的使用可能性。看: https://learn.microsoft.com/de-de/dotnet/csharp/language-reference/proposals/csharp-8.0/using

      【讨论】:

        猜你喜欢
        • 2010-11-22
        • 2011-03-21
        • 1970-01-01
        • 2018-11-18
        • 1970-01-01
        • 1970-01-01
        • 2014-04-04
        • 1970-01-01
        相关资源
        最近更新 更多