我有两个类,Person
和 Spouse
,这个方法检查配偶之间是否相等:
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;
}
如果 p1
或 p1.Spouse
为 null,则 p1?.Spouse
将为 null,在这种情况下 false
将被返回。
否则,我们知道 p1.Spouse
不为空,因此可以将它与 p2?.Spouse
进行比较。
关于c# - 简化空值检查和相等性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46927286/