【发布时间】:2017-10-17 19:08:42
【问题描述】:
我有以下代码:
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,那么运算符== 应该会自动遵循Equals 的行为,但事实并非如此。有什么原因吗?
【问题讨论】:
-
== 只检查引用相等
-
由于该语言允许您为您的班级覆盖
==,如果您选择不这样做,它不会在幕后这样做。 -
@Damien_The_Unbeliever:请注意,您不是覆盖,而是重载
==运算符。 -
你需要实现:public static bool operator ==(Person person1, Person person2)。看起来在 2010 年之前也有人问过同样的问题:stackoverflow.com/questions/4219261/…
-
您也应该重载 ==(和 !=)运算符。遵循these 指南
标签: c#