c# - 检查空引用

标签 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 而崩溃。当然,我可以编写代码来检查空引用的返回值,但这样代码会过于冗长。什么是优雅的方式来做到这一点?

最佳答案

您可以在 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")
        }
    );

不过,就我个人而言,我可能只是接受并明确地放入空测试:)

关于c# - 检查空引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2451516/

相关文章:

c# - 有没有一种方法可以使用 Roslyn 中的编译对象从引用的程序集中获取程序集级别的属性?

c# - 通过 LINQ 递归选择?

c# - 在 C# 中构建基于时间的异步服务的好方法

C# 无法转义正则表达式字符串中的引号

c# - IndexOf() 与 Replace() 和零宽度非连接器

c# - 如何检查我的收藏中是否有符合条件的记录?

c# - 异步编程中的跨线程异常

c# - SendAsync何时完成?

c# - 为什么我只有一部分 asp.net 成员表?

c# - 您如何让 XAML 元素缩放以适合其容器?