简体   繁体   English

对象引用未设置为foreach循环中C#中对象的实例?

[英]object reference not set to an instance of an object in C# in foreach loop?

foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]"))
{
//Code
}

this is my code where i get the exception please help me in sugesting me a solution 这是我得到异常的代码,请帮助我提出解决方案

Thanks in advance.......... 提前致谢..........

First stop... run the debugger and see if doc or doc.DocumentNode is null. 首先停止...运行调试器,查看docdoc.DocumentNode是否为null。 If not, then I would check your variable instances inside the loop, including link . 如果没有,那么我将在循环内检查您的变量实例,包括link

Always try debugging before asking questions... 在提出问题之前,请始终尝试调试...

make sure that doc or DocumentNode isn't null. 确保doc或DocumentNode不为null。

you can wrap your code like this. 您可以像这样包装代码。

if (doc!=null && doc.DocumentNode!=null)
{
     foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]"))
      {

      }
}

尝试doc.DocumentNode.SelectNodes("//a[@href]")返回null还是“ doc”为null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM