C#平等比较失败
通过iquapable<>
在以下类中,我在平等比较方面遇到了麻烦:
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
}
中发生了一个未手动的'system.stackoverflowException'的例外。
polymermotionsimulation.exe
我该如何解决?
I am having trouble with the equality comparison via IEquatable<>
in the following class I wrote:
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
How can I solve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的
==
操作员会自调用,导致无限递归。要检查对象是否为null引用,更好地使用是null
或 ReferenceEquals(a1,null):和
!=
的Similary。或者:
Your
==
operator calls itself, leading to infinite recursion. To check if an object is a null reference, better useis null
or ReferenceEquals(a1, null):and similary for
!=
.Or: