我在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

我該如何解決這個問題?
uj5u.com熱心網友回復:
您的==操作員呼叫自己,導致無限遞回。要檢查物件是否為空參考,最好使用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);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/465765.html
