如何避免多,如果null检查 [英] How to avoid multiple if null checks

查看:193
本文介绍了如何避免多,如果null检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能显示的文件:结果
深空检查,有没有更好的办法?结果
C#优雅的方式来检查,如果一个属性的属性为null






我必须做一个查找在这样一个深刻的对象模型:

  p.OrganisationalUnit.Parent.Head.CurrentAllocation.Person; 



反正是有evalute这一点,并返回null如果任何链为空(组织单位,父母,头,等),而不必做了。

 如果(p.org == NULL和放大器;&安培; p.org。家长== NULL和放大器;&安培;。p.org.Parent.Head 


解决方案

您正在寻找空安全引用操作(又称航行安全),有些语言(比如Groovy中)都有,但不幸的是C#中没有此运算符。



希望这将是实现1天....



另请参阅通过埃里克利珀这篇文章。语法他建议有


Possible Duplicates:
Deep Null checking, is there a better way?
C# elegant way to check if a property's property is null

i have to do a lookup in a deep object model like this:

  p.OrganisationalUnit.Parent.Head.CurrentAllocation.Person;

is there anyway to evalute this and return null if any of the chain is null (organizationalunit, parent, head, etc), without having to do a

if (p.org == null && p.org.Parent == null && p.org.Parent.Head . . .     

解决方案

You are looking for the null-safe dereference operator ?. (also known as safe navigation) that some languages (e.g. Groovy) have, but unfortunately C# does not have this operator.

Hopefully it will be implemented one day....

See also this post by Eric Lippert. The syntax he proposes there is .?.

这篇关于如何避免多,如果null检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆