9

好吧,我正在尝试创建一个小型应用程序来保存一些员工的姓名、年龄和薪水。所以我决定用Dictionary它来设置每个员工的工资,我想出了那个代码

代码

var employeeSalaryDictionary = new Dictionary<Employee, int>();
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 };
//or even
Employee employeeToFind = new Employee { Name = "Chuck"};

//Always False...
bool exists = employeeSalaryDictionary.ContainsKey(employeeToFind); 

员工类

public class Employee
{
    public string Name { get; set; }
    public int Age { get; set; }
}

但是,正如我注释掉或主题标题所述,尽管我尝试了两种方式,但.ContainsKey总是返回我False,如代码中所示。

4

2 回答 2

18

您没有使用接受的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);
        }
  }

但是,正如您所注意到的,您必须决定在创建字典时将使用哪个比较器进行键比较。以后改不了了。。。

于 2013-07-12T21:54:48.050 回答
3

Employee 是一个引用类型。当您添加新员工时,您的字典键将包含对该 Employee 对象的引用地址。如果您创建另一个 Employee 对象,它的引用与您的第一个 Employee 对象不同,即使它们包含相同的数据

于 2013-07-12T21:54:34.503 回答