c# - 在 C# 中,是否有一种干净的方法来检查多级空引用

标签 c# null reference-type

例如,如果我想调用以下内容: 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/

相关文章:

c# - 在 C# 中重新排序 BindingList 中的项目?

c# - 事件限制/排队 - react 性扩展?

c# - 将 null 作为默认参数传递以避免使用参数

java - 使用对象变量引用新的数据类型/对象

c# - 获取更新的 int 值

c# - Entity Framework 4.1 没有向 SQL Server Express 数据库添加任何行

c# - 错误的 ClientCredentials 的常见做法是什么?

android - Flutter/Firebase 项目 - `Unhandled Exception: Null check operator used on a null value` 是否导致黑屏?

java - 空参数检查、断言或异常哪个更好?

c# - 如何将父类引用的子类更改为具有子类的引用类型?