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法则.
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
| 归档时间: |
|
| 查看次数: |
6013 次 |
| 最近记录: |