c# - 简化空值检查和相等性

标签 c# null

我有两个类,PersonSpouse,这个方法检查配偶之间是否相等:

private bool SpousesSame(Person p1, Person p2)
{
    bool tempFlag = false;

    if (p1 != null && p2 != null && p1.Spouse != null && p2.Spouse != null && p1.Spouse == p2.Spouse)
    {
        tempFlag = true;
    }

    return tempFlag;
}

如您所见,有大量的空值检查(Person 也可以是 null)。 这可以简化吗?

编辑: 当两个人都为空时,我试图返回 false

最佳答案

private bool SpousesSame(Person p1, Person p2)
{
    return p1?.Spouse != null && p1.Spouse == p2?.Spouse;
}
如果 p1p1.Spouse 为 null,则

p1?.Spouse 将为 null,在这种情况下 false 将被返回。

否则,我们知道 p1.Spouse 不为空,因此可以将它与 p2?.Spouse 进行比较。

关于c# - 简化空值检查和相等性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46927286/

相关文章:

php - 检查值是否为空,如果是,则不打印任何内容,否则,打印值。帮助?

SQL如何插入空值

c# - NLOG,在 Windows Phone 8 上登录 SQLite

c# - 简单登录的 MVC 模式中组件的职责是什么

c# - null 和未初始化的区别?

c# - 具有 Null 值的 Oracle 11g odp.net 驱动程序问题

java - Class#getClassLoader 什么时候返回 null?

c# - 日志级别 : Would you consider DEBUG finer than TRACE?

c# - raisepropertychanged 和 PropertyChanged 有什么区别?

c# - 将imageUrl转换为byte[]进行缓存