.NET 流,在对象之间传递流,最佳实践 (C#)

.NET streams, passing streams between objects, best practices (C#)(.NET 流,在对象之间传递流,最佳实践 (C#))

本文介绍了.NET 流,在对象之间传递流,最佳实践 (C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在用 c# 编写一个小玩具汇编程序(正在阅读计算系统元素书.顺便说一下,这本书非常好.)

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 file path and removes junk (comments etc) lines.

然后将文件传递给解析器,最后传递给另一个创建二进制代码的模块.

The file is then passed to a parser then finally to a another module that creates the binary code.

这并不太复杂,但我不希望每次一个对象完成对输入文件的处理时都不必将临时文件写入文件系统.

This isn't too complicated, but I'd like not to have to write out a temporary file to the filesystem every time one object has finished it's processing of the input file.

我只想将流传递到下一个对象.我最初认为解析/垃圾删除中涉及的每个类都将实现 IDisposable ,但我认为这意味着我无法将流传递给下一个对象进行处理(流将被关闭,除非我将其全部保存在一个 using 语句中?).

I'd like to just pass the stream onto the next object. I originally thought each class involved in the parsing / junk removing would implement IDisposable but I think this means I can't pass the stream on the next object for processing (the stream would be closed, unless I keep it all in one using statement?).

我想我在这里遗漏了一些东西,是否有一种简单的方法可以干净地在对象之间传递流,或者我需要一种不同的方法?

I think I'm missing something here, is there a simple way to pass streams between objects cleanly, or do I need a different approach?

在此先感谢您的帮助!

推荐答案

一般来说,正确处理 Disposable 对象是消费者的责任.因此,如果您将 Stream 传递给另一个对象,则不应处置它 - 这是消费者的责任.

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.

所以在明确的场景中,要么你持有一个对 Disposable 对象的引用,在这种情况下你应该确保它被正确处置;或者您将引用传递给其他人并忘记它.

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.

那么如果你需要自己持有一个引用,但仍然传递它呢?在这些情况下,传递 Disposable 资源的副本 - 这将使您和使用者能够相互独立地管理两个实例的生命周期.但是,如果您遇到这种情况,您应该重新考虑您的设计,因为我称之为代码异味.

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.

这篇关于.NET 流,在对象之间传递流,最佳实践 (C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:.NET 流,在对象之间传递流,最佳实践 (C#)

基础教程推荐