我已经阅读过这个问题
我理解,实现==
、!=
和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.
那么,问题是 - 如何重载上述运算符并摆脱此错误?
public override bool Equals(object o)
еҗ—пјҹ - bansi!=
写成return !(obj1 == obj2)
的形式,这样就可以利用已经为==
重载所写的内容。 - drzaus