我使用以下代码片段,不确定是否需要调用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)指清除流的所有缓冲区,并导致任何缓冲数据被写入底层设备。
那在上述代码的上下文中意味着什么呢?
其次,
MemoryStream
的flush方法根据API文档什么也不做,那这是怎么回事呢?我们为什么要调用一个什么也不做的方法?