运算符重载==,!=,等于

我已经经历了一个问题

据我所知,有必要实现==!=Equals()

 public class BOX { double height, length, breadth; // this is first one '==' public static bool operator== (BOX obj1, BOX obj2) { return (obj1.length == obj2.length && obj1.breadth == obj2.breadth && obj1.height == obj2.height); } // this is second one '!=' public static bool operator!= (BOX obj1, BOX obj2) { return !(obj1.length == obj2.length && obj1.breadth == obj2.breadth && obj1.height == obj2.height); } // this is third one 'Equals' public override bool Equals(BOX obj) { return (length == obj.length && breadth == obj.breadth && height == obj.height); } } 

我假设,我已正确编写代码来覆盖==!=Equals运算符。 虽然,我得到编译错误如下。

 'myNameSpace.BOX.Equals(myNameSpace.BOX)' is marked as an override but no suitable method found to override. 

所以,问题是 – 如何覆盖上面的运算符并摆脱这个错误?

我想你宣布Equals方法是这样的:

 public override bool Equals(BOX obj) 

由于object.Equals方法接受一个对象,因此没有方法可以使用此签名覆盖。 你必须像这样覆盖它:

 public override bool Equals(object obj) 

如果你想要类型安全的Equals,你可以实现IEquatable

正如Selman22所说,你覆盖了默认的object.Equals方法,它接受一个object obj而不是一个安全的编译时类型。

为了实现这一点,请使您的类型实现IEquatable

 public class Box : IEquatable { double height, length, breadth; public static bool operator ==(Box obj1, Box obj2) { if (ReferenceEquals(obj1, obj2)) { return true; } if (ReferenceEquals(obj1, null)) { return false; } if (ReferenceEquals(obj2, null)) { return false; } return (obj1.length == obj2.length && obj1.breadth == obj2.breadth && obj1.height == obj2.height); } // this is second one '!=' public static bool operator !=(Box obj1, Box obj2) { return !(obj1 == obj2); } public bool Equals(Box other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } return height.Equals(other.height) && length.Equals(other.length) && breadth.Equals(other.breadth); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } return obj.GetType() == GetType() && Equals((Box)obj); } public override int GetHashCode() { unchecked { int hashCode = height.GetHashCode(); hashCode = (hashCode * 397) ^ length.GetHashCode(); hashCode = (hashCode * 397) ^ breadth.GetHashCode(); return hashCode; } } } 

另外需要注意的是,您使用等于运算符进行浮点比较,您可能会遇到精度损失。

实际上,这是一个“如何”的主题。 那么,这是参考实现:

  public class BOX { double height, length, breadth; public static bool operator == (BOX b1, BOX b2) { if (null == b1) return (null == b2); return b1.Equals(b2); } public static bool operator != (BOX b1, BOX b2) { return !(b1 == b2); } public override bool Equals(object obj) { if (obj == null || GetType() != obj.GetType()) return false; var b2 = (BOX)obj; return (length == b2.length && breadth == b2.breadth && height == b2.height); } public override int GetHashCode() { return height.GetHashCode() ^ length.GetHashCode() ^ breadth.GetHashCode(); } } 

参考: https : //msdn.microsoft.com/en-us/library/336aedhh(v = vs.100).aspx #Examples