我有一个类型,我在 IDictionary 中用作键。类型如下
public class Employee
{
public string Name { get; set; }
public int ID { get; set; }
public override bool Equals(object obj)
{
Employee emp = obj as Employee;
if (emp != null)
return emp.Name.Equals(this.Name);
return false;
}
public override int GetHashCode()
{
return this.Name.GetHashCode();
}
}
现在我在我的主目录中创建了一个字典,如下所示
IDictionary<Employee, int> empCollection = new Dictionary<Employee, int>();
Employee emp1 = new Employee() { Name = "abhi", ID = 1 };
Employee emp2 = new Employee() { Name = "vikram", ID = 2 };
Employee emp3 = new Employee() { Name = "vikram", ID = 3 };
empCollection.Add(emp1, 1);
empCollection.Add(emp2, 2);
empCollection.Add(emp3, 3);
现在在调试时我发现当将emp1添加到集合中时,仅调用键类型的GetHashCode方法,之后当将emp2添加到集合中时,仅再次调用GetHashCode方法,但在emp3的情况下,GetHashCode和Equals方法都被调用被称为。
问这个问题可能看起来太天真了,但是为什么在将 eqImp2 对象添加到集合时不调用 Equals 方法。里面发生了什么。请解释。