【发布时间】:2014-02-09 09:43:29
【问题描述】:
我使用以下 sn-p 代码,但我不确定是否需要调用 Flush 方法(一次在 StreamWriter 上,一次在 MemoryStream 上):
//converts an xsd object to the corresponding xml string, using the UTF8 encoding
public string Serialize(T t)
{
using (var memoryStream = new MemoryStream())
{
var encoding = new UTF8Encoding(false);
using (var writer = new StreamWriter(memoryStream, encoding))
{
var serializer = new XmlSerializer(typeof (T));
serializer.Serialize(writer, t);
writer.Flush();
}
memoryStream.Flush();
return encoding.GetString(memoryStream.ToArray());
}
}
首先,因为代码在using 块内,我认为自动调用的 dispose 方法可能会为我做这件事。这是真的,还是冲洗一个完全不同的概念?
根据stackoverflow本身:
Flush 意思是清除流的所有缓冲区,并导致任何缓冲的数据写入底层设备。
在上面的代码上下文中这是什么意思?
其次是MemoryStreamdoes nothing according to the api的flush方法,那是怎么回事呢?为什么我们调用一个什么都不做的方法?
【问题讨论】:
-
您不必执行 Flush(),因为您已经放置了“使用”:Writer/Reader 将在 Close/Dispose 时自动关闭其缓冲区。如果您想加载/保存时间结果(比如流的一半)并继续处理流,则 Flush() 很有用。