本文介绍了如果元素不存在,则检查空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在获取 .resx
文件中许多元素的值.在某些 data
元素上,< comment>
子元素不存在,因此当我运行以下命令时,我将得到一个 NullReferenceException
.
I am getting values for a number of elements in a .resx
file. On some of the the data
elements the <comment>
child element does not exist so when I run the following I will get a NullReferenceException
.
foreach (var node in XDocument.Load(filePath).DescendantNodes())
{
var element = node as XElement;
if (element?.Name == "data")
{
values.Add(new ResxString
{
LineKey = element.Attribute("name").Value,
LineValue = element.Value.Trim(),
LineComment = element.Element("comment").Value //fails here
});
}
}
我尝试了以下操作:
LineComment = element.Element("comment").Value != null ?
element.Element("comment").Value : ""
并且:
LineComment = element.Element("comment").Value == null ?
"" : element.Element("comment").Value
但是我仍然遇到错误?任何帮助表示赞赏.
However I am still getting an error? Any help appreciated.
推荐答案
使用空条件(?.
)运算符:
LineComment = element.Element("comment")?.Value
它用于在执行成员访问之前在 之前测试是否为空.
It used to test for null before performing a member access.
这篇关于如果元素不存在,则检查空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!