繁体   English   中英

C# 相等比较失败

[英]C# equality comparison fails

我在以下 class 中通过IEquatable<>进行相等比较时遇到了问题我写道:

public class Bead: IEquatable<Bead>
{
    public string Name { get; set; }
    public Point2d Location { get; private set; }

    public void SetLocation(Point2d newLocation)
    {
        Location = newLocation;
    }

    #region equality comparison
    /// <summary>
    /// Equality comparisons
    /// </summary>
    /// <param name="other"></param>
    /// <returns></returns>
    public override bool Equals(object other)
    {
        if (!(other is Bead)) return false;
        return Equals((Bead)other); // Calls method below
    }
    public bool Equals(Bead other) // Implements IEquatable<Point2d>
    {
        return Location == other.Location && Name == other.Name;
    }
    public override int GetHashCode()
    {
        return this.Location.GetHashCode() * 67 + Name.GetHashCode(); // 67 = some prime number
    }
    public static bool operator ==(Bead a1, Bead a2)
    {
        if (a1 == null && a2 == null) return true;
        if (a1 == null || a2 == null) return false;
        return a1.Equals(a2);
    }
    public static bool operator !=(Bead a1, Bead a2)
    {
        if (a1 == null || a2 == null) return true;
        if (a1 == null && a2 == null) return false;
        return !a1.Equals(a2);
    } 
    #endregion
}

An unhandled exception of type 'System.StackOverflowException' occurred in PolymerMotionSimulation.exe

在此处输入图像描述

我该如何解决这个问题?

您的==运算符调用自身,导致无限递归。 要检查 object 是否是 null 引用,最好使用is nullReferenceEquals(a1, null)

public static bool operator ==(Bead a1, Bead a2)
{
    if (a1 is null && a2 is null) return true;
    if (a1 is null || a2 is null) return false;
    return a1.Equals(a2);
}

!=相似。

或者:

public static bool operator ==(Bead a1, Bead a2)
{
    if (ReferenceEquals(a1, null) && ReferenceEquals(a2, null)) return true;
    if (ReferenceEquals(a1, null) || ReferenceEquals(a2, null)) return false;
    return a1.Equals(a2);
}

暂无
暂无

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

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