簡體   English   中英

C#GetHashCode / Equals覆蓋未調用

[英]C# GetHashCode/Equals override not called

我遇到了GetHashCode和Equals的問題,我已經覆蓋了一個類。 我使用operator ==來驗證兩者是否相等,並且如果它們的哈希碼相同以便驗證它們確實相等,我希望它將調用GetHashCode和Equals。

但令我驚訝的是,沒有被調用,並且相等測試的結果是錯誤的(雖然它實際上應該是真的)。

覆蓋代碼:

    public class User : ActiveRecordBase<User>

        [...]

        public override int GetHashCode()
        {
            return Id;
        }

        public override bool Equals(object obj)
        {
            User user = (User)obj;
            if (user == null)
            {
                return false;
            }

            return user.Id == Id;
        }
    }

平等檢查:

    if (x == y) // x and y are both of the same User class
    // I'd expect this test to call both GetHashCode and Equals

運算符==.GetHashCode().Equals()完全分開。

您可能對Microsoft 重載等於()和運算符==的指南感興趣。

簡短版本是:使用.Equals()來實現相等比較。 使用operator ==進行身份比較,或者如果要創建不可變類型(其中每個相等的實例可以被認為實際上相同)。 此外, .Equals()是一個虛方法,可以被子類覆蓋,但operator ==取決於使用它的表達式的編譯時類型。

最后,為了保持一致, .GetHashCode()實現.GetHashCode()都要實現.Equals() 重載運算符!=任何時候重載運算符==

也許在你的User類中再添加一個方法。

    public virtual bool Equals(User other) 
    {
        if (ReferenceEquals(null, other)) return false;
        if (ReferenceEquals(this, other)) return true;
        return other.Id == Id;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM