在内存中表示文本的最佳方式
我有两个继承自公共基类的类。
这些专门的类中的每一个都从数据库加载一些数据,对其进行处理,然后将该信息保存在文本文件中。
第一类将信息表示为 XML 文档。 第二个类将其信息存储为文本文件,并使用分隔符分隔字段。
我想要做的是在基类中编写一个可供两个类使用的 Save 方法。由于所有类都会写入文本文件,我正在考虑使用通用表示将其数据存储在内存中 - 例如,第一个类会将 XmlDocument 转换为该通用表示。
将其存储在内存、字符串、流中的最佳方式是什么?
谢谢
I have 2 classes that inherit from a common base class.
Each of these specialized classes load some data from a data base, process it and then save that information in text files.
The first class represents the information as a XML document.
The second class will store its information as a text file with delimiters separating fields.
What I want to do is to write a single Save method in the base class that can be used by both classes. As all classes will write to text files I was thinking in use a common representation to store their data in memory - for instance the first class will transform the XmlDocument to that common representation.
What is the best way to store this in memory, string, Stream?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果派生类以非常不同的方式表示数据,则不要为它们实现通用的 Save 方法,这些类最了解如何保存其数据。
将 Save() 抽象化并让每个子类实现保存。
执行 Save() 可能有一些共同点(例如打开实际文件、错误处理)。因此,让您的基类提供一个 Save() 方法,该方法负责调用每个子类实现的虚拟
Save(System.IO.TextWriter writer);
方法。If the derived classes represent the data very differently, don't implement a common Save method for them, Those classes knows best how to Save their data.
Make Save() abstract and have each of the subclass implement the saving.
There might be something in common for doing a Save() (e.g. opening the actual file, error handling). So have your base class provide a Save() method that's responsible for that which in turn calls a virtual
Save(System.IO.TextWriter writer);
method that each of your subclasses implement.鉴于 XML 是您提到的两种格式中更丰富的一种,并且相对容易操作,为什么不采用单一表示形式和 2 种保存方法呢?
Given that XML is the richer of the two formats you mention, and relatively easy to manipulate, why not have a single representation and 2 save methods?
如果输入数据的结构统一,您可以将其干净地存储在
DataSet
中,并且可以使用 DataSet.ReadXml 在TextReader
输入上。如果只有一种类型的记录要输出到分隔文本文件,DataTable 可以直接使用 - 一个
DataSet
封装了多个DataTable
。另一种替代方法可能是使用 XSLT 将 XML 直接转换为 CSV(此处逗号 = 分隔符,您可以使用您想要的任何内容),如下所示 此处,作者:@Welbog。
If the input data is uniformly structured, you can likely store it cleanly in a
DataSet
, and maybe load directly from your XML using DataSet.ReadXml on aTextReader
input.If you only have one type of record to output to the delimited textfile, DataTable could be used directly - a
DataSet
encapsulates multipleDataTable
s.Another alternative might be to convert XML directly to CSV (comma = delimiter here, you could use whatever you wanted though) using XSLT as shown here by @Welbog.