您没有使用接受的Dictionary
构造函数,IEqualityComparer<T>
也没有在类上实现自定义相等Employee
。
所以现在字典正在通过引用比较员工。当您new
是雇员时,您有不同的参考,即使名称可能相同。
可能这里最简单的方法是实现您自己的IEqualityComparer<Employee>
,您可以在其中选择哪些成员将用于相等比较,并将其传递给字典的构造函数。
[编辑] 正如所承诺的,片段:
//ReSharper's courtesy
public sealed class NameAgeEqualityComparer : IEqualityComparer<Employee>
{
public bool Equals(Employee x, Employee y)
{
if (ReferenceEquals(x, y)) return true;
if (ReferenceEquals(x, null)) return false;
if (ReferenceEquals(y, null)) return false;
if (x.GetType() != y.GetType()) return false;
return string.Equals(x.Name, y.Name) && x.Age == y.Age;
}
public int GetHashCode(Employee obj)
{
unchecked
{
return ((obj.Name != null ? obj.Name.GetHashCode() : 0) * 397) ^ obj.Age;
}
}
}
进而:
var employeeSalaryDictionary = new Dictionary<Employee, int>(new NameAgeEqualityComparer());
employeeSalaryDictionary.Add(new Employee { Name = "Chuck", Age = 37 }, 1000);
employeeSalaryDictionary.Add(new Employee { Name = "Norris", Age = 37 }, 2000);
employeeSalaryDictionary.Add(new Employee { Name = "Rocks", Age = 44 }, 3000);
Employee employeeToFind = new Employee { Name = "Chuck", Age = 37 };
bool exists = employeeSalaryDictionary.ContainsKey(employeeToFind); // true!
为了完整起见,这里是仅名称比较器(也是 ReSharper 的礼貌):
public sealed class NameEqualityComparer : IEqualityComparer<Employee>
{
public bool Equals(Employee x, Employee y)
{
if (ReferenceEquals(x, y)) return true;
if (ReferenceEquals(x, null)) return false;
if (ReferenceEquals(y, null)) return false;
if (x.GetType() != y.GetType()) return false;
return string.Equals(x.Name, y.Name);
}
public int GetHashCode(Employee obj)
{
return (obj.Name != null ? obj.Name.GetHashCode() : 0);
}
}
但是,正如您所注意到的,您必须决定在创建字典时将使用哪个比较器进行键比较。以后改不了了。。。