.Net 数据读取器的设计模式
您认为将某种文件类型读入我的应用程序的“理想”设计模式是什么?
我希望能够在不同的地方重用代码,所以显然我希望将其放在单独的 dll 中,但是尽管我可以将文件名或流传递到代码中,但是处理读取数据的推荐设计模式是什么。
从内存管理的角度来看,将所有数据读入数组并将其传递出去显然并不理想,但我能想到的唯一其他方法是在读取记录时引发事件,但这并不感觉“正确”是因为我担心某些事件可能会误入歧途。
我确信有一种非常巧妙的方法可以做到这一点,但我一辈子都想不到。
谢谢
What do you think the "ideal" design pattern for reading a certain file type into my application.
I want to be able to reuse the code in various places, so clearly I want to have this in a separate dll, however although I have no problem passing a filename or stream into the code, what's the recommended design pattern for handling the read data.
Reading all the data into an array and passing this out is obviously not ideal from a memory management point of view, but the only other way I can think of doing it is by raising events when a record is read, however this doesn't feel "right" in that I would be worried that some of the events could go astray.
I'm sure there's a really slick way of doing this, but I can't for the life of me think of it.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
格式是什么?如果是文本,则传入
TextReader
是理想的选择;对于 xml,是一个XmlReader
。如果是任意二进制,则传入一个Stream
。对于大数据,理想的方法尽可能是以非缓冲方式读取数据 - 即不要将其全部加载到内存中。迭代器块在这里可能很有用,例如,这是一个显示读取行的愚蠢示例(但它可以轻松地从流中的数据构建
yield return
对象):显然在一般情况下更多每个项目可能都需要处理!
调用者现在拥有一个延迟假脱机、非缓冲的数据源,例如:
处理流/文本读取器等允许他们在装饰器链中与文件以外的东西一起使用;网络流、内存流、压缩/加密流等。
What is the format? If it is text, passing in a
TextReader
would be ideal; and for xml, anXmlReader
. If it is arbitrary binary, pass in aStream
.For large data, the ideal approach where possible is to read the data in a non-buffered way - i.e. don't load it all into memory. Iterator blocks can be useful here, for example here's a silly example that shows reading lines (but it could just as easily
yield return
objects built from data in a stream):obviously in the general case a lot more processing may be necessary per item!
The caller now has a lazily-spooling, non-buffered source of your data, for example:
And handling stream/textreader etc allows them to use it in a decorator chain with things other than files; network streams, in-memory streams, compression/crypto streams, etc.
很难定义如此笼统的东西。您必须指定更多您真正需要的内容或文件类型。然后你可以看看.NET Framework本身,有很多“XXXReader”类,例如:
并且每个类都与其他类确实不同......有些是抽象的,有些不是,等等......
It's difficult to define something so general. You would have to specify more what you really need, or the file type. Then you can have a look at the .NET Framework itself, there are a lot of "XXXReader" classes, for example:
And each one is really different from the others... Some are abstract, some aren't, etc...