【问题标题】:c# System.ArgumentNullException: Value cannot be null. Parameter name: sourcec# System.ArgumentNullException:值不能为空。参数名称:来源
【发布时间】:2017-08-04 00:21:50
【问题描述】:

我创建的程序需要从网站读取信息,然后将其存储。我收到错误消息:

System.ArgumentNullException:值不能为空。
参数名称:source
在 System.Linq.Enumerable.Select[TSource,TResult](IEnumerable1 source, Func2 选择器)

但是它并不总是错误地运行。就像有时它起作用,有时它不起作用一样。怎么会这样? 这是给我第 4 行错误的代码。

IEnumerable<string> webtemp = Enumerable.Empty<string>();
if (datastring.Contains("today_nowcard-temp"))
{
    webtemp = doc.DocumentNode.SelectNodes("//div[@class = 'today_nowcard-temp']/span").Select(d => d.InnerText.Trim());

    foreach (var this_header in webtemp)
    {
        string[] temporary = this_header.Trim().Replace("Â", "-").Replace(" ", "-").Split('-');
        int f = (Convert.ToInt32(temporary[0]));
        _actualData[0].temp = GetCelsius(f);
        //Console.WriteLine(_actualData[0].temp);
    }
}

【问题讨论】:

  • this DocumentNode.SelectNodes("//div[@class = 'today_nowcard-temp']/span") 返回一个空值,但没有看到您在 doc 中拥有的内容,无法说明为什么 xpath 不返回结果。
  • 它有时会返回一个结果,据我所知,xpath 没有改变。
  • 我们需要查看您文档的 xml 是否是 @rene 获取的内容。
  • 看起来您遇到了类似的问题:stackoverflow.com/questions/38166949/…
  • @T.W.:即使您的 xpath 没有改变,您正在下载的文档也可能是。

标签: c# linq


【解决方案1】:

此异常背后的原因是您的 SelectNodes 方法返回的值。有时它返回 null 然后您尝试对 null 执行 Linq 操作并产生错误。所以你可以对此进行空检查

var temp= doc.DocumentNode.SelectNodes("//div[@class = 'today_nowcard-temp']/span");

if(temp != null){
//TODO
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-17
    • 2018-06-03
    • 2010-11-11
    • 2021-07-19
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 2013-04-23
    相关资源
    最近更新 更多