我有以下代码。
XElement opCoOptOff = doc.Descendants(ns + "OpCoOptOff").FirstOrDefault();
String opCo = opCoOptOff.Element(ns + "strOpCo").Value;
现在,如果我返回的元素为空,我将收到 NullReferenceException,因为 XElement 为空。所以我将其更改为以下内容。
String opCo = opCoOptOff.Element(ns + "strOpCo").Value;
if(opCoOptOff != null)
{
String opCo = opCoOptOff.Element(ns + "strOpCo").Value;
我希望必须有一种更优雅的方法来做到这一点,因为这种情况经常出现,我想避免每次出现问题时都进行这种类型的检查。任何帮助将不胜感激
最佳答案
你可以写一个 extension method
并在任何地方使用它:
public static class XDocumentExtension
{
public static string GetSubElementValue(this XElement element, string item)
{
if(element != null && element.Value != null)
{
if (element.Element(item) != null)
{
return element.Element(item).Value;
}
}
return null;
}
public static XElement GetElement(this XElement element, string item)
{
if (element != null)
return element.Element(item);
return null;
}
public static XElement GetElement(this XDocument document, string item)
{
if (document != null)
return document.Descendants("item").FirstOrDefault();
return null;
}
}
用作:
String opCo = opCoOptOff.Element(ns + "strOpCo").GetSubElementValue(ns + "strOpCo");
您还可以根据需要添加其他扩展。
编辑:我已经更新了答案,但如果你在我写之前仔细阅读它,你可以为你的目的添加其他扩展。
我写这个是因为我猜你可能想调用 null objects Element,我不知道你的具体情况,但我添加了一些代码来进一步说明,根据你的情况完成 XDocumentExtension 类,并且一个注释扩展方法可以在 null 对象上工作。
关于linq - XElement NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4704628/