如何避免多次if null检查

leo*_*ora 6 c# null

可能重复:
深度空检查,有更好的方法吗?
C#优雅的方法来检查属性的属性是否为null

我必须在这样的深对象模型中进行查找:

  p.OrganisationalUnit.Parent.Head.CurrentAllocation.Person;
Run Code Online (Sandbox Code Playgroud)

无论如何要评估这个并且如果任何链为null(organizationalunit,parent,head等)则返回null,而不必执行

if (p.org == null && p.org.Parent == null && p.org.Parent.Head . . .     
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 8

您正在寻找?.某些语言(例如Groovy)具有的null-safe dereference运算符(也称为安全导航),但遗憾的是C#没有此运算符.

希望有一天会实施....

另请参阅Eric Lippert的这篇文章.他提出的语法是.?.


Ces*_*Gon 7

你听说过得墨忒耳法吗?

链接如此长的呼叫序列并不是一个好主意.它会在您不需要的类之间创建可怕的依赖关系.

在您的示例中,包含的类p依赖于其他五个类.我建议你简化代码,让每个类在他们自己的知识环境中检查单个级别的空值.


Tho*_*que 6

看看这篇文章.它提供了一个很好的解决方案,可以让你写出这样的东西:

p.With(x => x.OrganisationalUnit)
 .With(x => x.Parent)
 .With(x => x.Head)
 .With(x => x.CurrentAllocation
 .With(x => x.Person);
Run Code Online (Sandbox Code Playgroud)