在 C# 中,是否有一种干净的方法来检查多个级别的空引用
例如,如果我想调用以下内容: person.Head.Nose.Sniff()
那么,如果我想安全,我必须执行以下操作:
if(person != null)
if(person.Head != null)
if(person.Head.Nose != null)
person.Head.Nose.Sniff();
有没有更简单的方法来制定这个表达式?
For example, if I want to call the following:person.Head.Nose.Sniff()
then, if I want to be safe, I have to do the following:
if(person != null)
if(person.Head != null)
if(person.Head.Nose != null)
person.Head.Nose.Sniff();
Is there any easier way of formulating this expression?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
首先,您可以利用布尔逻辑运算符中的短路并执行以下操作:
另请注意,您所做的事情违反了开发软件的设计指南,该指南称为 德墨忒尔定律。
First you can take advantage of short-circuiting in the boolean logic operators and do something like:
Also note that what you are doing goes against a design guideline for developing software that is known as Law of Demeter.
在 C# 6 中,您可以使用 null 条件运算符
?
。代码示例
这是打包到方法中的原始代码,并假设
Sniff()
始终返回true
:这是使用 C# 6 null 条件运算符重写的代码:
< code>?? 是 空合并运算符 且与你的问题无关。
有关完整示例,请参阅:
https://github.com/lernkurve/Stackoverflow-question-3701563
With C# 6, you can use the null-conditional operator
?
.Code example
This is your original code packed into a method and assuming
Sniff()
always returnstrue
:This is your code rewritten with the C# 6 null-conditional operator:
The
??
is the null-coalescing operator and is not related to your question.For the full example, see:
https://github.com/lernkurve/Stackoverflow-question-3701563
这是沿着同样提到的流畅参数验证的另一个实现:链式 null 检查和 Maybe monad
Here's another implementation along the lines of the also-mentioned Fluent Parameter Validation: Chained null checks and the Maybe monad
其实也不是,除此之外
Not really, besides
您可以使用空对象而不是空值。如果调用链中的任何对象是空对象,则
Sniff
将不执行任何操作。这不会引发异常:
您的 null 类可能如下所示(您也可以将它们用作单例,并具有
IPerson
、IHead
和INose
的接口code>):顺便说一句,在 Oxygene 中,有一个 运算符 用于此目的:
You could use null objects instead of null values.
Sniff
would then do nothing if any objects in the call chain are null objects.This would not throw an exception:
Your null classes could look like this (you could also use them as singletons and have interfaces for
IPerson
,IHead
andINose
):As a side note, in Oxygene there's an operator for this:
您可以使用Fluent参数验证< /a>
You can use Fluent Parameter Validation
最好的方法是使用
&&
运算符而不是嵌套的if
语句:请注意,从技术上讲,您可以执行类似的 null 检查使用表达式树。你的方法将有一个像这样的签名:
...这将允许你编写看起来像这样的代码:
但这将涉及反射,并且与 < 相比,通常更难以以任何深入的方式遵循code>&& 方法。
The best way is just to use the
&&
operator instead of nestedif
statements:Note that you technically could perform a similar null check using an expression tree. Your method would have a signature like this:
...which would allow you to write code looking something like this:
But this would involve reflection and would generally be much more difficult to follow in any sort of in-depth way compared to the
&&
method.我会摆脱对 null 的任何使用,并执行如下操作:
这将需要某种基本的类或接口。
I would get rid of any use of
null
and do something like this:This would require some kind of base
class
orinterface
.