C# - 嵌套的 using 语句是否多余?

标签 c# filestream dispose streamreader using

我在 MSDN 文档中看到了以下示例代码,演示了如何使用 System.IO.StreamReader 类从 System.IO.FileStream< 读取 UTF-8 文本 对象。这两个嵌套的 using 语句让我觉得是多余的——肯定是在其中一个对象上调用 Dispose() 就可以解决问题,并正确释放文件句柄? (来源:http://msdn.microsoft.com/en-us/library/yhfzs7at.aspx)

using (FileStream fs = new FileStream(path, FileMode.Open)) 
{
    using (StreamReader sr = new StreamReader(fs)) 
    {

        while (sr.Peek() >= 0) 
        {
            Console.WriteLine(sr.ReadLine());
        }
    }
}

用以下方式重写该代码不是更简单且同样正确吗?

using (FileStream fs = new FileStream(path, FileMode.Open)) 
{
    StreamReader sr = new StreamReader(fs);

    while (sr.Peek() >= 0) 
    {
        Console.WriteLine(sr.ReadLine());
    }
}

最佳答案

根据文档,The StreamReader object calls Dispose() on the provided Stream object when StreamReader.Dispose is called .这意味着使用 StreamReader 保证处理底层Stream。反之亦然:仅处理 Stream 就足够了 - StreamReader 可能正在分配其他 native 资源。所以第二个样本不正确。

(仅使用 StreamReader 不涵盖 StreamReader 构造函数可能抛出的情况。为了涵盖这种情况,需要使用 。因为它只抛出不可读或 null 流,所以这可能不相关。)

一般来说,您应该始终处置每个一次性元素。它是 IDisposable 协定的一部分,多次处置一个对象并没有什么坏处,而且这样做的开销很低。

关于C# - 嵌套的 using 语句是否多余?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25827072/

相关文章:

c++ - ofstream ifilestream 并使用 cin 获取字符数组?

c# - C#文件流在写/读操作完成之前不会阻塞

java - 使用 JButton 通过 addActionListener 处理 JFrame

c# - 自定义自动调整大小的WPF面板类

c# - 如何在不实际单击按钮的情况下触发 Button Click 事件?

C# 两个类和两个表链接

c# - 如何强制 MVC4 中的 WebAPI 在 json 结果中将空字符串呈现为空

java - 如何在Android应用程序中保存不确定量的信息?

reporting-services - 处理时的 SSRS ReportViewer nullreference 异常

c# - 在 C# 中重用或处理自定义字体的有效方法