.NET streams, passing streams between objects, best practices (C#)

后端 未结 4 2126
温柔的废话
温柔的废话 2020-12-31 12:31

I\'m currently writing a little toy assembler in c# (going through the elements of computing systems book. Really good book by the way.)

The assembler takes an input

相关标签:
4条回答
  • 2020-12-31 12:37

    If something else is using the stream after the assembler is done with it, the assembler shouldn't "own" the stream. The caller should either create a stream for the assembler (and subsequent modules) to use, or the assembler should return a new stream which it is then the caller's responsibility to close.

    It would be instructive to see some more details on what your program's architecture looks like and what methods we are discussing here.

    0 讨论(0)
  • 2020-12-31 12:38

    In general, it is the responsibility of the consumer to properly dispose of a Disposable object. As such, if you pass off a Stream to another object, you shouldn't Dispose it - that would be the responsibility of the consumer.

    So in the clear-cut scenarios, either you hold a reference to a Disposable object, in which case you should ensure that it is properly disposed; or you pass the reference to someone else and forget about it.

    Then what about the cases where you need to hold a reference yourself, but still pass it along? In these cases, pass a copy of the Disposable resource - this will alow you and the consumer to manage the lifetime of the two instances independently of each other. However, if you get into this situation, you should reconsider your design, as I would call that a code smell.

    0 讨论(0)
  • 2020-12-31 12:54

    Overall, I agree with the previous comments. However if your model doesn't fit that, you could do what Microsoft did with the XML Writer: It accepts an XMLWriterSettings parameter when you instance it, and one of the properties of the settings object describes whether the writer should close the underlying stream when the writer is disposed.

    0 讨论(0)
  • 2020-12-31 12:54

    The way I did these projects in TECS is:

    • read each line in the file
    • trim the whitespace at the beginning and end of the line
    • if the line is blank or if it starts with // then go to the next line
    • otherwise, store the line in an array (in C#, I actually use a List<string> object)

    Once I've gone through all of the lines, I can close my file stream and safely do my work on the array of lines.

    0 讨论(0)
提交回复
热议问题