简体   繁体   English

用Equals()覆盖相等运算符

[英]Override the equality operators with Equals()

I've been debugging an issue for quite some time and realize that it was coming from the usage of an == on a object where I should have used the object.Equals() 我已经调试了一个问题很长时间了,并且意识到这是由于我应该使用对象的情况下对对象使用==导致的object.Equals()

In order to prevent such issue, would like that the == operator calls the Object.Equals() that I have overridden. 为了防止此类问题,希望==运算符调用我已重写的Object.Equals()

Is that possible? 那可能吗? The following code runs into a Stack-overflow exception... 以下代码遇到堆栈溢出异常...

public static bool operator ==(Portfolio a, Portfolio b)
{
    return a != null && a.Equals(b);
}

public static bool operator !=(Portfolio a, Portfolio b)
{
    return a != null && !a.Equals(b);
}

Thanks! 谢谢!

You're recursively calling the != operator from your != operator, hence the stack overflow. 您从!=运算符递归调用!=运算符,因此堆栈溢出。 Use ReferenceEquals instead: 使用ReferenceEquals代替:

public static bool operator !=(Portfolio a, Portfolio b)
{
    return !object.ReferenceEquals(a, null) && !a.Equals(b);
}

That said, this code is flawed because it'll return false if a is null and b isn't. 就是说,此代码存在缺陷,因为如果a为null而b为非,它将返回false You should check both objects for null: 您应该检查两个对象是否为空:

public static bool operator !=(Portfolio a, Portfolio b)
{
    if (object.ReferenceEquals(a, null))
    {
        return !object.ReferenceEquals(b, null);
    }

    return !a.Equals(b);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM