提问人:user366312 提问时间:4/27/2022 更新时间:4/27/2022 访问量:56
C# 相等性比较失败
C# equality comparison fails
问:
我在等式比较方面遇到了麻烦,在我写的以下课程中: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
我该如何解决这个问题?
答:
8赞
Klaus Gütter
4/27/2022
#1
运算符调用自身,导致无限递归。要检查对象是否为 null 引用,最好使用 或 ReferenceEquals(a1, null):==
is 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);
}
评论