在C#中,是否有一种检查多级空引用的简洁方法

And*_*ker 18 c# null reference-type

例如,如果我想调用以下内容: person.Head.Nose.Sniff() 那么,如果我想要安全,我必须执行以下操作:

if(person != null)
    if(person.Head != null)
        if(person.Head.Nose != null)
            person.Head.Nose.Sniff();
Run Code Online (Sandbox Code Playgroud)

是否有更简单的方法来制定这个表达式?

Joã*_*elo 18

首先,您可以利用布尔逻辑运算符中的短路,并执行以下操作:

if (person != null && person.Head != null && person.Head.Nose != null)
{
    person.Head.Nose.Sniff();
}
Run Code Online (Sandbox Code Playgroud)

另请注意,您所做的事情与开发软件的设计指南相违背,该软件称为Demeter法则.

  • *"我更喜欢它被称为Demeter的偶尔有用的建议."*Martin Fowler http://haacked.com/archive/2009/07/14/law-of-demeter-dot-counting.aspx (2认同)

Ler*_*rve 13

是否有更简单的方法来制定这个表达式?

使用C#6,您可以使用空条件运算符 ?.

代码示例

这是您的原始代码打包到方法中并假设Sniff()始终返回true:

    public bool PerformNullCheckVersion1(Person person)
    {
        if (person != null)
            if (person.Head != null)
                if (person.Head.Nose != null)
                    return person.Head.Nose.Sniff();
        return false;
    }
Run Code Online (Sandbox Code Playgroud)

这是用C#6空条件运算符重写的代码:

    public bool PerformNullCheckVersion2(Person person)
    {
        return person?.Head?.Nose?.Sniff() ?? false;
    }
Run Code Online (Sandbox Code Playgroud)

??null-coalescing运算符,与您的问题无关.

有关完整示例,请参阅:https: //github.com/lernkurve/Stackoverflow-question-3701563


jem*_*ick 7

这是另外一个实现,也就是前面提到的Fluent参数验证: 链式空检查和Maybe monad