检查空引用

时间:2010-03-16 01:04:12

标签: c#

我有以下代码:

searchResults.SearchResultCollection.Add(
                new SearchResult()
                    {
                        Header =
                        HttpUtility.HtmlDecode(
                        htmlDocument.DocumentNode
                        .SelectSingleNode(initialXPath + "h3") 
                        .InnerText),
                        Link = HttpUtility.HtmlDecode(
                        htmlDocument.DocumentNode
                        .SelectSingleNode(initialXPath + "div/cite")
                        .InnerText)
                    }
                );

有时htmlDocument.DocumentNode.SelectSingleNode(....)返回null,我的应用程序因NullReferenceException而崩溃。当然,我可以编写代码来检查null引用的返回值,但代码将过于冗长。这样做的优雅方式是什么?

4 个答案:

答案 0 :(得分:3)

你可以在XmlNode上创建一个扩展方法,如下所示:

public static class ExtensionMethods
{
    public string GetNodeText(this XmlNode node, string xPath)
    {
        var childNode = node.SelectSingleNode(xPath);
        return (childNode == null)
            ? "" : childNode.InnerText;
    }
}

searchResults.SearchResultCollection.Add(
    new SearchResult()
        {
            Header = HttpUtility.HtmlDecode(
                    htmlDocument.DocumentNode.GetNodeText(initialXPath + "h3"),
            Link = HttpUtility.HtmlDecode(
                    htmlDocument.DocumentNode.GetNodeText(initialXPath + "div/cite")
        }
    );

就个人而言,我可能只是简单地把它搞砸了并明确地进行了空测试:)

答案 1 :(得分:3)

创建SelectSingleNode的试用版作为扩展方法。

public static class XmlNodeExtensions
{
    public static bool TrySelectSingleNode(this XmlNode node,
                                           string xpath,
                                           out XmlNode result)
    {
        result = node.SelectSingleNode(xpath);
        return (result != null);
    }
}

然后您将代码更改为:

XmlNode node;
searchResults.SearchResultCollection.Add(
    new SearchResult
    {
        Header = HttpUtility.HtmlDecode(
            htmlDocument.DocumentNode
                .TrySelectSingleNode(initialXPath + "h3", out node)
                    ? node.InnerText
                    : null),
        Link = HttpUtility.HtmlDecode(
            htmlDocument.DocumentNode
                .TrySelectSingleNode(initialXPath + "div/cite", out node)
                    ? node.InnerText
                    : null)
    });

答案 2 :(得分:2)

只需编写扩展方法。

public static class Extensions
{
   public static String SafeInnerText(this XmlElement node, String default)
   {
      return (node != null) ? node.InnerText : default;
   }
}

然后按如下方式使用它。

[...].SelectSingleNode(initialXPath + "h3").SafeInnerText("NoInnerText");

是的,我知道,default是保留关键字...

答案 3 :(得分:1)

我不知道检查null是如何过于冗长。如果你在各处做同样的事情(拉出一个节点)。您可以将其抽象为执行空检查的单个方法/函数。这样,在尝试获取节点的任何地方都不会进行空检查,因为空检查被整齐地封装在函数/方法中。

否则,我认为您必须执行显式空检查。可能还有其他方法可以做到,但要小心。优雅,聪明,和hackish之间有一个很好的界限。 ;)