例如,如果我想调用以下内容:
person.Head.Nose.Sniff()
那么,如果我想安全起见,我必须执行以下操作:
if(person != null)
if(person.Head != null)
if(person.Head.Nose != null)
person.Head.Nose.Sniff();
有没有更简单的方法来表达这个表达式?
最佳答案
首先,您可以利用 bool 逻辑运算符中的短路并执行以下操作:
if (person != null && person.Head != null && person.Head.Nose != null)
{
person.Head.Nose.Sniff();
}
另请注意,您的所作所为违反了名为 Law of Demeter 的软件开发设计指南。 .
关于c# - 在 C# 中,是否有一种干净的方法来检查多级空引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3701563/