尽管检查为NULL,但为空引用异常
问题描述:
我正在从具有名为Col1,Col2等节点的动态生成数的C#读取XML文件。当我试图在这些节点上运行while循环并检查null我仍然得到一个NullReferenceException。任何人都可以建议如何处理这个以避免异常?尽管检查为NULL,但为空引用异常
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();
}
答
既然你在注释错误发生检查状况时,只有在那里你应该得到一个错误少数病例中提到:调用while循环在你面前
if(nodes == null)
{
// was nodes not populated? Then populate it
}
if(nodes[0][colCount] == null)
{
// does element actually exist or is it null?
}
检查这些条件应该找出导致问题的原因。
+0
谢谢dotnetom。看着你的解决方案,我意识到发生了异常,因为我在一个不存在的对象上调用了InnerText方法。修改后的while循环:while(nodes [0] [colCount]!= null) – 2014-11-08 21:11:46
是否将'timeToFillValues'初始化为一个值?或者它是'空'? – dotnetom 2014-11-08 20:06:33
timeToFillValues已初始化:var timeToFillValues = new列表(); 但是,NullReferenceException发生在while循环的开始处:while(nodes [0] [colCount] .InnerText!= null) –
2014-11-08 20:23:23
您在哪里得到异常?它是在循环内还是在循环中检查条件? – dotnetom 2014-11-08 20:24:55