c# - 如何处理 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;
}
}
解决方案
使用空条件运算符:
if (htmlDoc.GetElementbyId("shippingMessage_ftinfo_olp_1")?.InnerText != null)
如果htmlDoc
可以为空,也将其更改为htmlDoc?.GetEle....
推理:如果正在评估的对象为 null,则 null 条件运算符会使评估短路,从而防止您获得异常,有利于评估为 null。
推荐阅读
- jsf - 当 showTime 设置为 true 时 PrimeFaces 7.0 DatePicker 抛出 JS TypeError
- javascript - 根据键和值javascript的对象数组
- postgresql - PostgreSQL:触发器更新
- flutter - 颤振:父重建后未重建子小部件
- python-3.x - 未找到图像渲染器(点),不执行任何其他操作
- css - 响应式 div 小部件散景
- postgresql - 使用 PostgreSQL 更新 NESTED JSONB 数组中的对象
- php - 我将手机号码存储在数据库中,但有些手机号码存储如 954E+11,953E+11
- android - 如何使用多个部分和每个部分的数据源填充分页 RecyclerView?
- c# - 如何将标签控件保存为png图像