【发布时间】:2011-05-12 06:43:59
【问题描述】:
可能重复:
How do I check for nulls in an ‘==’ operator overload without infinite recursion?
这可能有一个简单的答案......但它似乎在逃避我。这是一个简化的例子:
public class Person
{
public string SocialSecurityNumber;
public string FirstName;
public string LastName;
}
假设对于这个特定的应用程序,如果社会安全号码匹配,并且两个名字匹配,那么我们指的是同一个“人”。
public override bool Equals(object Obj)
{
Person other = (Person)Obj;
return (this.SocialSecurityNumber == other.SocialSecurityNumber &&
this.FirstName == other.FirstName &&
this.LastName == other.LastName);
}
为了保持一致,我们也为团队中不使用 .Equals 方法的开发人员覆盖 == 和 != 运算符。
public static bool operator !=(Person person1, Person person2)
{
return ! person1.Equals(person2);
}
public static bool operator ==(Person person1, Person person2)
{
return person1.Equals(person2);
}
很好,花花公子,对吧?
但是,当 Person 对象为 null 时会发生什么?
你不能写:
if (person == null)
{
//fail!
}
因为这将导致 == 运算符覆盖运行,并且代码将在以下位置失败:
person.Equals()
方法调用,因为您不能在空实例上调用方法。
另一方面,您不能在 == 覆盖中明确检查此条件,因为它会导致无限递归(以及 Stack Overflow [dot com])
public static bool operator ==(Person person1, Person person2)
{
if (person1 == null)
{
//any code here never gets executed! We first die a slow painful death.
}
return person1.Equals(person2);
}
那么,如何覆盖 == 和 != 运算符以实现值相等并仍然考虑空对象?
我希望答案不是简单得令人痛苦。 :-)
【问题讨论】:
-
SO 正在阻止对这个问题的进一步回答,但从 C# 7 开始,最好的解决方案是使用新的
is null构造,即if (person1 is null) ... -
@Ross,无法添加答案,因为这是一个重复的问题。此外,如果您想指出原始问题的
is null构造,您会发现其他人在您发表评论前 2 年已经回答了这个问题。 -
@gog 可能是这样,但这个问题在 Google 搜索中排名第一。似乎......令人难以置信的误导......让这个页面充满(现在)错误的答案没有得到纠正,希望人们会点击重复的链接,而不是使用这个页面上高度赞成和可行但过时的答案之一.如果 SO 的目标是提供帮助,则应尽一切努力完全删除此页面,或使其尽可能好。
标签: c# .net null overloading operator-keyword