Я должен сделать StreamWriter.flush ()?

Напишите небольшие методы. Кажется, что программисты любят писать более длинные методы, где они делают несколько разных вещей.

Я думаю, что метод должен быть создан везде, где вы можете назвать его.

27
задан H. Pauwelyn 18 December 2017 в 17:42
поделиться

2 ответа

Scratch the previous answer - I hadn't noticed that you were using two wrappers around the same stream. That feels somewhat risky to me.

Either way, I'd put the StreamWriter and BinaryWriter in their own using blocks.

Oh, and yes, it's legal to call ToArray() on the MemoryStream - the data is retained even after it's disposed.

If you really want to use the two wrappers, I'd do it like this:

using (MemoryStream stream = new MemoryStream())
{
    using (StreamWriter normalWriter = new StreamWriter(stream))
    using (BinaryWriter binaryWriter = new BinaryWriter(stream))
    {
        foreach(...)
        {
            binaryWriter.Write(number);
            binaryWriter.Flush();
            normalWriter.WriteLine(name); //<~~ easier to read afterward.
            normalWriter.Flush();
        }
    }    
    return MemoryStream.ToArray();
}

I have to say, I'm somewhat wary of using two wrappers around the same stream though. You'll have to keep flushing each of them after each operation to make sure you don't end up with odd data. You could set the StreamWriter's AutoFlush property to true to mitigate the situation, and I believe that BinaryWriter currently doesn't actually require flushing (i.e. it doesn't buffer any data) but relying on that feels risky.

If you have to mix binary and text data, I'd use a BinaryWriter and explicitly write the bytes for the string, fetching it with Encoding.GetBytes(string).

24
ответ дан 28 November 2019 в 05:48
поделиться

Обновление

Не обращайте внимания на этот ответ, я запутался с авторами ...


  1. Нет, порядок будет сохранен ( обновление: может и нет). Промывка полезна / необходима в других ситуациях, хотя я не могу вспомнить, когда.
  2. Думаю, что да, использование гарантирует, что все хорошо очищается.
0
ответ дан 28 November 2019 в 05:48
поделиться
Другие вопросы по тегам:

Похожие вопросы: