给定以下类别

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很重要?


当前回答

怎么样:

public override int GetHashCode()
{
    return string.Format("{0}_{1}_{2}", prop1, prop2, prop3).GetHashCode();
}

假设性能不是问题:)

其他回答

在我看来,考虑到公共财产,下面使用反射似乎是一个更好的选择,因为在此情况下,您不必担心财产的添加/删除(尽管不太常见)。我发现这也表现得更好。(使用诊断学秒表比较时间)。

    public int getHashCode()
    {
        PropertyInfo[] theProperties = this.GetType().GetProperties();
        int hash = 31;
        foreach (PropertyInfo info in theProperties)
        {
            if (info != null)
            {
                var value = info.GetValue(this,null);
                if(value != null)
                unchecked
                {
                    hash = 29 * hash ^ value.GetHashCode();
                }
            }
        }
        return hash;  
    }

从C#9(.net5或.netcore3.1)开始,您可能希望使用记录,因为默认情况下它使用基于值的相等。

怎么样:

public override int GetHashCode()
{
    return string.Format("{0}_{1}_{2}", prop1, prop2, prop3).GetHashCode();
}

假设性能不是问题:)

这是因为框架要求两个相同的对象必须具有相同的哈希代码。如果重写equals方法来对两个对象进行特殊比较,并且该方法认为这两个对象是相同的,那么两个对象的哈希代码也必须相同。(字典和哈希表依赖于这一原则)。

我们有两个问题要解决。

如果对象可以更改。此外,对象通常不会用于依赖于GetHashCode()的集合。因此实现GetHashCode()通常不值得,或者不值得可能的如果有人将您的对象放入调用GetHashCode(),并且您已重写Equals()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()
    {
        // Some comment to explain if there is a real problem with providing GetHashCode() 
        // or if I just don't see a need for it for the given class
        throw new Exception("Sorry I don't know what GetHashCode should do for this class");
    }
}