![](/img/trans.png)
[英]Why are you expected to override GetHashCode and Equals when overloading the equality operator?
[英]Overriding Equals and GetHashCode doesn't necessarily override equality overloading operator
我有以下代码:
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=true
, getHashCodeNum=true
,但isEqual2=false
。
我希望由于我已经重写了Equals
和GetHashCode
,所以operator ==
应该自动遵循Equals
的行为,但事实并非如此。 任何原因?
==
是运营商 。 你可以在两个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);
}
}
==
和!=
是对:你需要实现!=
如果你实现==
反之亦然,否则你得到错误:
错误CS0216:运算符
Person.operator ==(Person, Person)
需要匹配的运算符!=
也要定义
现在当你比较两个Person
它应该有效。 但是请注意,不要覆盖相等运算符, 否则 会使它们超载 。 所以编译器会选择==
实现(这不是在运行时通过动态绑定完成的)。 结果是:
bool isEqual2 = p1 == p2; //true
bool isEqual3 = (object) p1 == p2; //false
bool isEqual4 = p1 == (object) p2; //false
bool isEqual5 = (object) p1 == (object) p2; //false
默认情况下, ==
over两个object
是引用相等,所以只有当这两个参数是Person
,我们检查这两个对象是否相同 。
因此,如果要使用动态绑定检查相等性,则最好使用Equals(..)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.