在.NET GetHashCode方法中,很多地方都使用.NET 方法.特别是在快速查找集合中的项目或确定相等性时.是否有关于如何GetHashCode为我的自定义类实现覆盖的标准算法/最佳实践,因此我不会降低性能?
我写了一个自定义比较器类.
public class ItemComparer : IEqualityComparer<Item>
{
public int GetHashCode(Item x)
{
return (x == null) ? 0 : new { x.Name, x.CompanyCode,
x.ShipToDate, x.Address }.GetHashCode();
}
Run Code Online (Sandbox Code Playgroud)
当我新建两个项目并比较哈希码时,我的测试失败了.为什么哈希不同?
[TestMethod]
public void Two_New_Items_Have_The_Same_Hash_Code()
{
// arrange
var comparer = new ItemComparer();
Item x = new Item();
Item y = new Item();
// act
int xHash = comparer.GetHashCode(x);
int yHash = comparer.GetHashCode(y);
// assert
Assert.AreEqual(xHash, yHash);
}
Run Code Online (Sandbox Code Playgroud)
编辑 - 这是完整的课程.我简单地使用上面的例子来简洁,但需要更多的信息
public class DtoPolicy : DtoBase
{
[Description("The Policy Number")]
public string PolicyNumber …Run Code Online (Sandbox Code Playgroud)