尽管检查Null,仍然为Null Reference Exception

时间:2014-11-08 20:00:32

标签: nullreferenceexception

我正在使用C#读取XML文件,该文件具有动态生成的名为Col1,Col2等的节点数。当我尝试在这些节点上运行while循环并检查null时,我仍然得到NullReferenceException 。任何人都可以建议如何处理这个以避免异常?

int col = 1;
string colCount = col.ToString();
colCount = "Col" + colCount;
while (nodes[0][colCount].InnerText != null)
{
   timeToFillValues.Add(double.Parse(nodes[0][colCount].InnerText));
   col++;
   colCount = "Col" + col.ToString();
}

1 个答案:

答案 0 :(得分:0)

由于您在评论中提到错误在检查条件时发生,因此只有少数情况下您应该收到错误:

if(nodes == null)
{
    // was nodes not populated? Then populate it
}
if(nodes[0][colCount] == null)
{
    // does element actually exist or is it null?
}

在调用while循环之前检查这些条件,你应该发现导致问题的原因。