0

我正在向字符串列表添加项目,我知道存在要插入的数据,但我不断收到空引用错误消息Object reference not set to an instance of an object.

    public class ExcelRow
        {
            public List<String> lstCells;
            public byte[] rowHash;
            ......
        }
    public class ExcelInfo
        {
            public List<ExcelRow> excelRows;
        }

    public ExcelInfo ReadExcel(OpenFileDialog openFileDialog)
        {
            var _excelFile = new ExcelQueryFactory(openFileDialog.FileName);
            var _info = from c in _excelFile.WorksheetNoHeader() select c;

            ExcelRow excelRow;
            ExcelInfo resp;

            resp = new ExcelInfo();

            foreach (var item in _info)
            {
                excelRow = new ExcelRow();
                excelRow.lstCells.Add(item.ElementAt(0));
                excelRow.lstCells.Add(item.ElementAt(1));
                excelRow.lstCells.Add(item.ElementAt(2));
                excelRow.lstCells.Add(item.ElementAt(3));
                .....
                excelRow.CalculateHash();
                resp.excelRows.Add(excelRow);
             }
            return resp;
       }

这是我得到错误的地方:excelRow.lstCells.Add(item.ElementAt(0));

4

2 回答 2

2

您需要在构造函数中初始化您lstCellsExcelRow

public class ExcelRow {
  public List<String> lstCells;
  public byte[] rowHash;
  public ExcelRow(){
     lstCells = new List<string>();
  }
  //....
}

public class ExcelInfo {
  public List<ExcelRow> excelRows = new List<ExcelRow>();
}
于 2013-08-27T01:48:21.913 回答
1

您没有显示您的ExcelRow构造函数,但是从错误中,我猜您永远不会实例化lstCells并且它仍然为空。

您可以通过调试程序并将鼠标悬停在行中的每个项目上或有条不紊地从行中一次删除一个项目直到它再次开始工作来发现这一点。并推断问题。

于 2013-08-27T01:49:16.400 回答