当前位置: 首页 > 编程语言 > C#

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

时间:2023-04-11 01:00:36 C#

运算符重载==,!=,equals我遇到过一个问题据我所知,必须实现==,!=andEquals()。publicclassBOX{double高度,长度,宽度;//这是第一个'=='publicstaticbooloperator==(BOXobj1,BOXobj2){return(obj1.length==obj2.length&&obj1.breadth==obj2.breadth&&obj1.height==obj2。高度);}//这是第二个'!='publicstaticbooloperator!=(BOXobj1,BOXobj2){return!(obj1.length==obj2.length&&obj1.breadth==obj2.breadth&&obj1.height==obj2.height);}//这是第三个'Equals'publicoverrideboolEquals(BOXobj){return(length==obj.length&&breadth==obj.breadth&&height==obj.height);我假设我已经正确地编写了代码来覆盖==、!=、等于运算符。虽然,我收到如下编译错误。“myNameSpace.BOX.Equals(myNameSpace.BOX)”被标记为覆盖但没有找到合适的方法来覆盖。所以,问题是——如何覆盖上面的运算符并消除这个错误?我认为您可以这样声明Equals方法:publicoverrideboolEquals(BOXobj)由于object.Equals方法采用一个对象,因此没有方法可以使用此签名进行覆盖。你必须像这样覆盖它:publicoverrideboolEquals(objectobj)如果你想要类型安全的Equals,你可以实现IEquatable。正如Selman22所说,您正在覆盖默认的object.Equals方法,该方法接受对象obj而不是安全的编译时类型。为了实现这一点,请使用您的类实现IEquatable:publicclassBox:IEquatable{doubleheight,length,breadth;publicstaticbooloperator==(Boxobj1,Boxobj2){if(ReferenceEquals(obj1,obj2)){返回真;}if(ReferenceEquals(obj1,null)){返回false;}if(ReferenceEquals(obj2,null)){返回false;}返回(obj1.length==obj2.length&&obj1.breadth==obj2.breadth&&obj1.height==obj2.height);}//这是第二个'!='publicstaticbooloperator!=(Boxobj1,Boxobj2){return!(obj1==obj2);}publicboolEquals(Boxother){if(ReferenceEquals(null,other)){returnfalse;}if(ReferenceEquals(this,other)){返回真;}returnheight.Equals(other.height)&&length.Equals(other.length)&&breadth.Equals(other.breadth);}publicoverrideboolEquals(objectobj){if(ReferenceEquals(null,obj)){returnfalse;}if(ReferenceEquals(this,obj)){返回真;}返回obj.GetType()==GetType()&&Equals((Box)对象);}publicoverrideintGetHashCode(){unchecked{inthashCode=height.GetHashCode();hashCode=(hashCode*397)^length.GetHashCode();hashCode=(hashCode*397)^breadth.GetHashCode();返回哈希码;}}}另一件需要注意的事情是,您正在使用等于运算符进行浮点比较,您可能会遇到精度损失实际上,这是一个“如何”的主题。所以,这里是参考实现:publicclassBOX{doubleheight,length,breadth;publicstaticbooloperator==(BOXb1,BOXb2){if(null==b1)return(null==b2);返回b1。等于(b2);}publicstaticbooloperator!=(BOXb1,BOXb2){return!(b1==b2);}publicoverrideboolEquals(objectobj){if(obj==null||GetType()!=obj.GetType())returnfalse;varb2=(BOX)obj;返回(长度==b2.length&&breadth==b2.breadth&&height==b2.height);}publicoverrideintGetHashCode(){returnheight.GetHashCode()^length.GetHashCode()^breadth.GetHashCode();}}参考:https://msdn.microsoft.com/en-us/library/336aedhh(v=vs.100).aspx#Examples以上是C#学习教程:运算符重载==,!=,等于分享的所有内容,如果对你有用,需要了解更多C#学习教程,希望大家多多关注~本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: