C#刷新StreamWriter和MemoryStream [英] C# flushing StreamWriter and a MemoryStream

查看:175
本文介绍了C#刷新StreamWriter和MemoryStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码段,并且不确定是否需要调用Flush方法(在StreamWriter上一次,在MemoryStream上一次):

I use the following snippet of code, and I'm unsure whether I need to call the Flush methods (once on StreamWriter, once on 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方法可能会对我有用.这是真的,还是冲洗是一个完全不同的概念?

First of all, because the code is inside the using block, I think the automatically called dispose method might do this for me. Is this true, or is flushing an entirely different concept?

根据stackoverflow本身:

According to stackoverflow itself:

Flush表示清除流的所有缓冲区,并使所有缓冲的数据写入底层设备.

在上面的代码中这是什么意思?

What does that mean in the context of the code above?

第二,MemoryStream

Secondly, the flush method of the MemoryStream does nothing according to the api, so what's up with that? why do we call a method that does nothing?

推荐答案

您不需要在StreamWriter上使用Flush,因为您正在处理它(通过将其放在using块中).丢弃后,它会自动刷新并关闭.

You don't need to use Flush on the StreamWriter, as you are disposing it (by having it in a using block). When it's disposed, it's automatically flushed and closed.

您不需要在MemoryStream上使用Flush,因为它不会缓冲写入任何其他源的任何内容.根本没有要冲洗的地方.

You don't need to use Flush on the MemoryStream, as it's not buffering anything that is written to any other source. There is simply nothing to flush anywhere.

Flush方法仅出现在MemoryStream对象中,因为它继承自Stream类.您可以在源代码中找到MemoryStream flush方法实际上不执行任何操作.

The Flush method is only present in the MemoryStream object because it inherits from the Stream class. You can see in the source code for the MemoryStream class that the flush method actually does nothing.

这篇关于C#刷新StreamWriter和MemoryStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆