如果我有一个文件流的成员,像这样一类:如何关闭StreamReader/StreamWriter流对象作为类成员?
public class FooBar
{
private StreamReader reader;
private StreamWriter writer;
public FooBar(string readerFilePath, string writerFilePath)
{
reader = new StreamReader(readerFilePath);
writer = new StreamWriter(writerFilePath);
}
...
}
那我怎么关闭这些流?
看来,他们是在课程销毁期间默认关闭的,但是我不得不使用writer.Flush()
这听起来不太好。
FooBar的应该实现IDisposable。请参阅[正确实施IDisposable](https://msdn.microsoft.com/en-us/library/ms244737.aspx?f=255&MSPPError=-2147217396)和[正确实施IDisposable](https://stackoverflow.com/a/18337005/2066142) – KiwiPiet
如果我必须显式调用Dispose()方法,仍然不会在IDisposable接口背后得到原因。在我的特殊情况下,我不能使用'using'关键字。如果我试图在析构函数中调用'writer.Close()'(我会用C++的方式),我得到一个异常,告诉流已经关闭。 –
也许我必须了解垃圾收集器如何工作... –