gpt4 book ai didi

c# - 运算符重载 ==, !=, Equals

转载 作者:IT王子 更新时间:2023-10-29 03:57:13 25 4
gpt4 key购买 nike

我已经完成了 question

我理解,有必要实现==!=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.

因此,问题是 - 如何覆盖上述运算符并消除此错误?

最佳答案

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

为了实现这一点,让你的类型实现 IEquatable<Box> :

public class Box : IEquatable<Box>
{
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.Equals(obj2);
}
public static bool operator !=(Box obj1, Box obj2) => !(obj1 == obj2);
public bool Equals(Box other)
{
if (ReferenceEquals(other, null))
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) => Equals(obj as Box);

public override int GetHashCode()
{
unchecked
{
int hashCode = height.GetHashCode();
hashCode = (hashCode * 397) ^ length.GetHashCode();
hashCode = (hashCode * 397) ^ breadth.GetHashCode();
return hashCode;
}
}
}

另一件需要注意的事情是,您正在使用相等运算符进行浮点比较,您可能会遇到精度损失。

关于c# - 运算符重载 ==, !=, Equals,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25461585/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com