这个问题和 Jon 的回答让我意识到这甚至存在,所以我很好奇并启动了 Visual Studio。
我遵循了 MSDN 页面的一个示例,然后创建了自己的小示例。如下:
public class Person : IEquatable<Person>
{
public string IdNumber { get; set; }
public string Name { get; set; }
public bool Equals(Person otherPerson)
{
if (IdNumber == otherPerson.IdNumber)
return true;
else
return false;
}
public override bool Equals(object obj)
{
if (obj == null)
return base.Equals(obj);
if (!(obj is Person))
throw new InvalidCastException("The Object isn't of Type Person.");
else
return Equals(obj as Person);
}
public override int GetHashCode()
{
return IdNumber.GetHashCode();
}
public static bool operator ==(Person person1, Person person2)
{
return person1.Equals(person2);
}
public static bool operator !=(Person person1, Person person2)
{
return (!person1.Equals(person2));
}
}
所以我有几个问题:
如果 Equals 方法在处理我的自定义相等方面做得很好,为什么我还必须重写 GetHashCode 方法?
在比较类似下面的内容时,使用哪个比较器,Equals 还是 GetHashCode?
.
static void Main(string[] args)
{
Person sergio = new Person() { IdNumber = "1", Name = "Sergio" };
Person lucille = new Person() { IdNumber = "2", Name = "Lucille" };
List<Person> people = new List<Person>(){
sergio,
lucille
};
Person lucille2 = new Person() { IdNumber = "2", Name = "Lucille" };
if (people.Contains(lucille2))
{
Console.WriteLine("Already exists.");
}
Console.ReadKey();
}
- 运算符方法到底是做什么的?看起来那里正在发生某种伏都教黑魔法。