.NET流,传递对象之间的数据流,最佳实践(C#) [英] .NET streams, passing streams between objects, best practices (C#)

查看:468
本文介绍了.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每个类,但我想这意味着我不能下一个对象传递流进行处理(流将被关闭,除非我把它全部一个使用的语句?)。

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?

在此先感谢您的帮助!

推荐答案

在一般情况下,它是消费者的责任正确处置一个一次性的对象。因此,如果你是流通关到另一个对象,你不应该处置它 - 这将是消费者的责任

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.

那么关于你需要持有自己的参考,但仍沿它传递的情况下?在这些情况下,通过一次性资源的副本 - 这将alow你和消费者彼此独立地管理两个实例的寿命。但是,如果你陷入这种情况,你应该重新考虑你的设计,因为我会说这就是一个代码味道。

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#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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