文件阅读器封装在表读者中

时间:2012-03-06 17:42:39

标签: c#

我有一个文件阅读器对象,我需要读取包含表格的文件。我想创建一个名为Table的对象来保存读取文件中的行和列数据。问题是,要读取整个页面,我需要有一个表列表(文件中有多个表)。什么是我班级的最佳结构,这样我就不会过多地暴露数据阅读器并将其传递得过多?

我目前的想法是:

  1. 创建一个实例化表列表的类,并将该类传递给读者。
  2. 运行阅读器,找到每个新表,实例化一个新的表对象,并将引用传递给阅读器,以便获取行/列信息。
  3. 这是完成此类任务的最佳方式吗?或者是否有一种更有效的设计来限制读者被过多地传递?我必须使用using语句,并且在这个嵌套设计中使用它感觉不对

    由于

2 个答案:

答案 0 :(得分:0)

我个人认为将Table集合封装在您自己的类中以控制读者。如果隐藏这些细节是一个问题,我也不会允许公开实例化任何一个对象。这样的事情。

public class TableCollection : List<Table>
{
   private TableCollection() { }

   public static TableCollection FromFile(string filePath)
   {
       using (StreamReader reader = new StreamReader(filePath))
       {
           //populate all tables here before disposing
       }
   }
}

public class Table
{
   //whatever other properties/methods

   //keep it internal to hide the implementation from the user
   internal Table(StreamReader reader)
   {
      //do what you need to do here
   }
}

答案 1 :(得分:0)

您可以使用已有的DataTable。使用它们有一点点开销,但它听起来就好像它可以很容易使用。

您确实说过这些表包含不同的结构。文件中是否有任何标识表的更改?如果同一文件中有许多“表”,这可能会使其变得更加困难。

如果您想要一个列表,可以简单地使用DataTable类型的集合。如果你的设计需要,我想你可以为此创建自己的类。

List<DataTable> tables = new List<DataTable>();

以及如何使用它的示例方法:

private IList<DataTable> GetTables()
{
    IList<DataTable> tables = new List<DataTable>();
    using (StreamReader reader = new StreamReader(pathAndFile))
    {
        //pseudo-code below
        //Iterate through tables in the file: foreach(DiscoveredTable table in file)
        //parse from csv: table = GetTableFromCsv(table.DataFromTheFile);
        //add to tables collection: tables.Add(table);
    }

    return tables;
}

Here是指向CSV解析器的链接,如果您对该路由感兴趣,因为您说它是以逗号分隔的。

相关问题