在.NET GetHashCode方法中,很多地方都使用.NET 方法.特别是在快速查找集合中的项目或确定相等性时.是否有关于如何GetHashCode为我的自定义类实现覆盖的标准算法/最佳实践,因此我不会降低性能?
鉴于以下课程
public class Foo
{
public int FooId { get; set; }
public string FooName { get; set; }
public override bool Equals(object obj)
{
Foo fooItem = obj as Foo;
if (fooItem == null)
{
return false;
}
return fooItem.FooId == this.FooId;
}
public override int GetHashCode()
{
// Which is preferred?
return base.GetHashCode();
//return this.FooId.GetHashCode();
}
}
Run Code Online (Sandbox Code Playgroud)
我已经覆盖了该Equals方法,因为它Foo代表了Foos表的一行.哪个是覆盖的首选方法GetHashCode?
覆盖为什么重要GetHashCode?
简短的问题
如何实现GetHashCode一个Array.
细节
我有一个覆盖的对象Equals,检查:
this.array[n] == otherObject.array[n]
Run Code Online (Sandbox Code Playgroud)
所有n在array.
当然,我应该实施补充GetHashCode.我想知道是否有.NET方法可以做到这一点,或者我是否应该实现自己的方式
hash = hash ^ array[n]
Run Code Online (Sandbox Code Playgroud)
澄清
我的对象包含一个数组,我对GetHashCode感兴趣的数组元素.我的数组等价代码仅作为示例 - 就像我的问题所说,但也许我不清楚,我对GetHashCode(不是Equals)感兴趣.我说我自然应该实现补充,GetHashCode因为一旦Equals被覆盖(为了Dictionary正常运行等),实现这一点是.NET的要求.谢谢.
我想使用 HashSet.Contains 方法,因为它超级快。
var hashset = new HashSet<Customer>(customers, new CustomerComparer());
var found = hashset.Contains(new Customer{ Id = "1234", Name = "mit" }); // "mit" instead of an equals "smith" in the comparer.
Run Code Online (Sandbox Code Playgroud)
我在客户对象上搜索多个属性。
我必须实现 IEqualityComparer 接口,如:
public class CustomerComparer : IEqualityComparer<Customer>
{
public bool Equals(Customer x, Customer y)
{
return x.Id == y.Id && x.Name.Contains(y.Name);
}
public int GetHashCode(Customer obj)
{
return obj.Id.GetHashCode() ^ obj.Name.GetHashCode();
}
}
Run Code Online (Sandbox Code Playgroud)
当我不在 CustomerComparer Equals 方法中使用 Equals 方法(如 .Contains)时,为什么 Equals 方法永远不会命中?