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

后端 未结 4 2125
温柔的废话
温柔的废话 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: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.

提交回复
热议问题