首页 > 解决方案 > 如何处理 HtmlDocument 空异常

问题描述

我正在通过调用的 html id 检查 HtmlDocument()shippingMessage_ftinfo_olp_1但问题是我无法检查这是否为空异常。因为当我设置 if!=null仍然它抛出异常。任何人都可以告诉我如何检查它是否为 null 而没有这个例外?

System.NullReferenceException:“对象引用未设置为对象的实例。”

HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(response);
string gerLang = "";
if (htmlDoc.GetElementbyId("shippingMessage_ftinfo_olp_1").InnerText != null)
{
    gerLang = htmlDoc.GetElementbyId("shippingMessage_ftinfo_olp_1").InnerText;
    if(gerLang.Contains("AmazonGlobal Express-Zustellung"))
    {
        _outOfStock = false;
    }
}

图片

标签: c#

解决方案


使用空条件运算符

if (htmlDoc.GetElementbyId("shippingMessage_ftinfo_olp_1")?.InnerText != null)

如果htmlDoc可以为空,也将其更改为htmlDoc?.GetEle....

推理:如果正在评估的对象为 null,则 null 条件运算符会使评估短路,从而防止您获得异常,有利于评估为 null。


推荐阅读