运算符重载 ==, !=, Equals [英] Operator overloading ==, !=, Equals
问题描述
我已经看过问题
我明白,有必要实现==
、!=
和Equals()
.
I understand that, it is necessary to implement ==
, !=
and 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
运算符.但是,我得到如下编译错误.
I assume, I've written code properly to override ==
,!=
,Equals
operators. Though, I get compilation errors as follows.
'myNameSpace.BOX.Equals(myNameSpace.BOX)' is marked as an override
but no suitable method found to override.
所以,问题是 - 如何覆盖上述运算符 &摆脱这个错误?
So, question is - How to override above operators & get rid of this error?
推荐答案
我认为您像这样声明了 Equals
方法:
I think you declared the Equals
method like this:
public override bool Equals(BOX obj)
因为 object.Equals
方法接受一个对象,所以没有方法可以用这个签名覆盖.你必须像这样覆盖它:
Since the object.Equals
method takes an object, there is no method to override with this signature. You have to override it like this:
public override bool Equals(object obj)
如果你想要类型安全的Equals,
你可以实现IEquatable
.
If you want type-safe Equals,
you can implement IEquatable<BOX>
.
这篇关于运算符重载 ==, !=, Equals的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!