當覆蓋Equals方法時,覆蓋GetHashCode爲何很重要?

問題:

Given the following class 鑑於如下課程 ide

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

I have overridden the Equals method because Foo represent a row for the Foo s table. 我已經覆蓋了Equals方法,由於Foo表明的一排Foo桌上。 Which is the preferred method for overriding the GetHashCode ? 重寫GetHashCode的首選方法是? this

Why is it important to override GetHashCode ? 重寫GetHashCode爲何很重要? spa


解決方案:

參考一: https://stackoom.com/question/1YbA/當覆蓋Equals方法時-覆蓋GetHashCode爲何很重要
參考二: https://oldbug.net/q/1YbA/Why-is-it-important-to-override-GetHashCode-when-Equals-method-is-overridden
相關文章
相關標籤/搜索