gpt4 book ai didi

c# - 重写 Equals 和 GetHashCode 不一定会重写相等重载运算符

转载 作者:行者123 更新时间:2023-12-01 22:47:42 26 4
gpt4 key购买 nike

我有以下代码:

public enum ClassType
{
I,
II,

}

public enum LocationType
{
A,
B
}
public class Person
{
public LocationType LocType
{ get; set; }
public ClassType ClaType
{ get; set; }


public override bool Equals(object obj)
{
Person obPer = obj as Person;
if (obPer == null)
return false;
if (LocType != obPer.LocType)
return false;
if (ClaType != obPer.ClaType)
return false;
return true;

}

public override int GetHashCode()
{
return LocType.GetHashCode()^ClaType.GetHashCode();
}

}

static void Main(string[] args)
{

var p1 = new Person()
{
ClaType = ClassType.I,
LocType = LocationType.A
};


var p2 = new Person()
{
ClaType = ClassType.I,
LocType = LocationType.A
};

bool isEqual1 = p1.Equals(p2); //true
bool getHashCodeNum = p1.GetHashCode() == p2.GetHashCode(); //true
bool isEqual2 = p1 == p2; //false
}

我发现 isEqual1=truegetHashCodeNum=true,但 isEqual2=false

我希望由于我已经重写了 EqualsGetHashCode,因此运算符 == 应该自动遵循 的行为等于,但事实并非如此。有什么理由吗?

最佳答案

== 是一个运算符。您可以在两个 Person重载 == 运算符,如下所示:

public class Person {

//..

public static bool operator == (Person a, Person b)
{
if (Object.ReferenceEquals(a,null) && Object.ReferenceEquals(b,null))
return true;
if (Object.ReferenceEquals(a,null) || Object.ReferenceEquals(a,null))
return false;
return a.LocType == b.LocType && a.ClaType != b.ClaType;
}

public static bool operator != (Person a, Person b)
{
return ! (a == b);
}

}

==!= 是成对的:如果实现 ==,则需要实现 !=反之亦然,否则你会得到错误:

error CS0216: The operator Person.operator ==(Person, Person) requires a matching operator != to also be defined

现在,当您比较两个 Person 时,它应该可以工作。但请注意,您不是覆盖相等运算符,而是重载它们。因此,编译器选择==实现(这不是在运行时通过动态绑定(bind)完成)。结果是:

bool isEqual2 = p1 == p2;  //true
bool isEqual3 = (object) p1 == p2; //false
bool isEqual4 = p1 == (object) p2; //false
bool isEqual5 = (object) p1 == (object) p2; //false

默认情况下,两个对象上的==引用相等,所以只有当两个参数是Person时>在这里,我们检查两个人是否等价

因此,如果您想通过动态绑定(bind)检查相等性,最好使用 Equals(..)

关于c# - 重写 Equals 和 GetHashCode 不一定会重写相等重载运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44039787/

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