gpt4 book ai didi

c# - Dictionary.ContainsKey 总是返回 False

转载 作者:太空狗 更新时间:2023-10-29 17:34:12 30 4
gpt4 key购买 nike

好吧,我正在尝试创建一个小型应用程序来保存一些员工的姓名、年龄和薪水。所以我决定使用 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 尽管我尝试了两种方式,如中所示代码。

最佳答案

您没有使用 Dictionary接受 IEqualityComparer<T> 的构造函数你也没有在 Employee 上实现自定义相等性类。

所以现在字典是通过引用来比较员工。当你new员工,你有一个不同的引用,即使例如名称可能相同。

这里最简单的方法可能是实现您自己的 IEqualityComparer<Employee> ,您可以在其中选择哪些成员将用于相等比较,并将其传递给字典的构造函数。

[编辑] 正如 promise 的那样,片段:

//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);
}
}

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

关于c# - Dictionary.ContainsKey 总是返回 False,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17624582/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com