gpt4 book ai didi

c# - 重写 == 运算符。如何与 null 进行比较?

转载 作者:IT王子 更新时间:2023-10-29 03:33:21 25 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
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()

方法调用,因为您不能在空实例上调用方法。

另一方面,您不能在 == 覆盖中显式检查此条件,因为它会导致无限递归(和堆栈溢出 [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);
}

那么,您如何重写 == 和 != 运算符以获得值相等性并仍然考虑空对象?

我希望答案不是那么简单。 :-)

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com