【问题标题】:Necessary to explicitly close a stream in c# [duplicate]需要在 C# 中显式关闭流 [重复]
【发布时间】:2022-01-13 11:59:07
【问题描述】:

我遇到过这样的代码:

            using (StreamReader myStream = new StreamReader(responseStream))
            {
                response = myStream.ReadToEnd();
                myStream.Close();   //Is this necessary?
            }

我不认为这个 .Close() 语句是必要的。我的理解是,一旦我们跳出 using 语句的最后一个括号,流就会关闭,对吧?

【问题讨论】:

标签: c# stream


【解决方案1】:

是的,你不需要关闭流,这是使用块的好处。 只需要下面几行

using (StreamReader myStream = new StreamReader(responseStream))
        {
            response = myStream.ReadToEnd();
        }

参考这个链接: What is the purpose of the Using block in C#

【讨论】:

  • 您可以投票关闭这个问题作为另一个问题的副本,而不是从另一个答案复制(一旦你有足够的代表)
猜你喜欢
  • 2014-07-16
  • 1970-01-01
  • 2020-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-15
相关资源
最近更新 更多