我使用以下代码段,并且不确定是否需要调用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
does nothing according to the api的冲洗方法,那是怎么回事?为什么我们调用什么都不做的方法?
[您不需要在Flush
上使用StreamWriter
,因为您正在处理它(将其放在using
块中)。处置后,会自动冲洗并关闭。
您不需要在Flush
上使用MemoryStream
,因为它不会缓冲写入任何其他源的任何内容。根本没有要冲洗的地方。
Flush
方法仅在MemoryStream
对象中存在,因为它继承自Stream
类。您可以在source code for the MemoryStream
class中看到MemoryStream
方法实际上不执行任何操作。
通常,Streams将在写入数据时对数据进行缓冲(如果有的话,会定期将缓冲区刷新到关联的设备),因为写入设备(通常是文件)的开销很大。 MemoryStream写入RAM,因此缓冲和刷新的整个概念都是多余的。数据始终已经在RAM中。
是的,处理流将导致其被冲洗。
注释刷新方法返回空字节[],尽管我正在使用using块
flush