处理 streamreader 会关闭流吗?

Does disposing streamreader close the stream?(处理 streamreader 会关闭流吗?)
本文介绍了处理 streamreader 会关闭流吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在向要写入的方法发送流,并且在这些方法中我使用的是二进制读取器/写入器.当读取器/写入器被处理时,无论是通过 using 还是没有被引用,流是否也关闭了??

I am sending a stream to methods to write on, and in those methods I am using a binary reader/wrtier. When the reader/writer gets disposed, either by using or just when it is not referenced, is the stream closed as well??

我会发送一个 BinaryReader/Writer,但我也在使用 StreamReader(也许我应该解决这个问题.我只将它用于 GetLine 和 ReadLine).如果每次关闭写入器/读取器时它都关闭流,这将非常麻烦.

I would send a BinaryReader/Writer, but I am using a StreamReader too (maybe I should go around that. I am only using that for GetLine and ReadLine). This is quite troublesome if it closes the stream each time a writer/reader gets closed.

推荐答案

Yes, StreamReader, StreamWriter, BinaryReader and BinaryWriter 当您对它们调用 Dispose 时,所有它们都会关闭/处理它们的底层流.如果读取器/写入器只是垃圾收集,它们不会处理流-您应该始终处理读取器/写入器,最好使用 using 语句.(事实上,这些类都没有终结器,也不应该有.)

Yes, StreamReader, StreamWriter, BinaryReader and BinaryWriter all close/dispose their underlying streams when you call Dispose on them. They don't dispose of the stream if the reader/writer is just garbage collected though - you should always dispose of the reader/writer, preferrably with a using statement. (In fact, none of these classes have finalizers, nor should they have.)

就我个人而言,我也更喜欢对流使用 using 语句.您可以非常整齐地嵌套 using 不带大括号的语句:

Personally I prefer to have a using statement for the stream as well. You can nest using statements without braces quite neatly:

using (Stream stream = ...)
using (StreamReader reader = new StreamReader(stream, Encoding.Whatever))
{
}

即使流的 using 语句有些多余(除非 StreamReader 构造函数抛出异常)我认为这是最佳实践,因为如果你摆脱了StreamReader 并在以后直接使用流,您已经拥有正确的处理语义.

Even though the using statement for the stream is somewhat redundant (unless the StreamReader constructor throws an exception) I consider it best practice as then if you get rid of the StreamReader and just use the stream directly at a later date, you'll already have the right disposal semantics.

这篇关于处理 streamreader 会关闭流吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to know if a field is numeric in Linq To SQL(如何在 Linq To SQL 中知道字段是否为数字)
Extract sql query from LINQ expressions(从 LINQ 表达式中提取 sql 查询)
LINQ Where in collection clause(LINQ Where in collection 子句)
Orderby() not ordering numbers correctly c#(Orderby() 没有正确排序数字 c#)
Why do I get quot;error: ... must be a reference typequot; in my C# generic method?(为什么我会收到“错误:...必须是引用类型?在我的 C# 泛型方法中?)
Strange LINQ Exception (Index out of bounds)(奇怪的 LINQ 异常(索引越界))