重写==操作符。如何比较空?重写、操作

2023-09-03 09:08:17 作者:一個人的浪漫

可能重复:   How我检查空值在没有无限递归的'=='运算符重载?

有可能是一个简单的答案,这...但它似乎在躲避我。下面是一个简单的例子:

There is probably an easy answer to this...but it seems to be eluding me. Here is a simplified example:

public class Person
{
   public string SocialSecurityNumber;
   public string FirstName;
   public string LastName;
}

让我们说这个特定的应用程序,它是有效的说,如果社会安全号码匹配,并且这两个名字匹配,那么我们指的是同一个人。

Let's say that for this particular application, it is valid to say that if the social security numbers match, and both names match, then we are referring to the same "person".

public override bool Equals(object Obj)
{
    Person other = (Person)Obj;
    return (this.SocialSecurityNumber == other.SocialSecurityNumber &&
        this.FirstName == other.FirstName &&
        this.LastName == other.LastName);
}

要保持一致性,我们覆盖了==和!=运算符,也为在不使用 .Equals 方法,谁的团队开发。

To keep things consistent, we override the == and != operators, too, for the developers on the team who don't use the .Equals method.

public static bool operator !=(Person person1, Person person2)
{
    return ! person1.Equals(person2);
}

public static bool operator ==(Person person1, Person person2)
{
    return person1.Equals(person2);
}

好得很,对吧?

Fine and dandy, right?

然而,发生了什么

您可以不写:

if (person == null)
{
    //fail!
}

由于这将导致==操作符重载运行,而code将无法在:

Since this will cause the == operator override to run, and the code will fail on the:

person.Equals()

方法调用,因为你不能在空实例调用的方法。

method call, since you can't call a method on a null instance.

在另一方面,你不能显式地检查==覆盖这里面的情况,因为这将导致无限递归(和堆栈溢出[点com])

On the other hand, you can't explicitly check for this condition inside the == override, since it would cause an infinite recursion (and a 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, how do you override the == and != operators for value equality and still account for null objects?

我希望答案是没有痛苦地简单。 : - )

I hope that the answer is not painfully simple. :-)

推荐答案

使用 object.ReferenceEquals(PERSON1,空)而不是 == 操作符:

public static bool operator ==(Person person1, Person person2)
{
    if (object.ReferenceEquals(person1, null))
    {
         return object.ReferenceEquals(person2, null);
    }

    return person1.Equals(person2);
}