【发布时间】:2019-02-02 10:02:16
【问题描述】:
给定以下类
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();
}
}
我已经覆盖了Equals 方法,因为Foo 代表Foos 表的一行。覆盖GetHashCode 的首选方法是什么?
为什么覆盖GetHashCode很重要?
【问题讨论】:
-
由于冲突,特别是在使用字典时,实现 equals 和 gethashcode 很重要。如果两个对象返回相同的哈希码,它们将通过链接插入到字典中。访问 item 时使用 equals 方法。
-
使用 Visual Studio,我们可以根据我们的类道具生成 Equals() 和 GetHashCode()。看到这个链接。 docs.microsoft.com/en-us/visualstudio/ide/reference/…
-
GetHashCode 对我来说总是很困难
标签: c# overriding hashcode