C#刷新StreamWriter和一个MemoryStream
发布时间:2020-12-15 23:41:59 所属栏目:百科 来源:网络整理
导读:我使用下面的代码片段,我不确定是否需要调用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 M
我使用下面的代码片段,我不确定是否需要调用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本身:
在上面的代码中,这意味着什么? 其次,MemoryStream does nothing according to the api的flush方法,那有什么用呢?为什么我们称之为无效的方法? 解决方法
您不需要在StreamWriter上使用Flush,因为您正在处理它(通过将其放在using块中).当它被丢弃时,它会自动冲洗并关闭.
您不需要在MemoryStream上使用Flush,因为它不会缓冲写入任何其他源的任何内容.任何地方都没有什么可以冲洗的. Flush方法仅存在于MemoryStream对象中,因为它继承自Stream类.你可以在source code for the (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |