覆盖 == 运算符.如何与空值进行比较?

时间:2022-11-04
本文介绍了覆盖 == 运算符.如何与空值进行比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

可能的重复:
如何检查空值在没有无限递归的=="运算符重载中?

对此可能有一个简单的答案……但我似乎无法回答.这是一个简化的例子:

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);
}

很好很花哨,对吧?

但是,当 Person 对象为 null 时会发生什么?

However, what happens when a Person object is null?

你不能写:

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

因为这将导致 == 运算符覆盖运行,并且代码将失败:

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.

另一方面,您无法在 == 覆盖中明确检查此条件,因为它会导致无限递归(和堆栈溢出 [dot 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, null) 或新的 is 运算符 而不是 == 运算符:

Use object.ReferenceEquals(person1, null) or the new is operator instead of the == operator:

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

    return person1.Equals(person2);
}

这篇关于覆盖 == 运算符.如何与空值进行比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一条:成员访问中的问号在 C# 中是什么意思? 下一条:Equals(item, null) 或 item == null

相关文章

最新文章