2008-09-16 86 views
6

實現Equals()參考類型比看起來更難。我目前的規範執行是這樣的:對於引用類型,Equals()的「最佳」規範實現是什麼?

public bool Equals(MyClass obj) 
{ 
    // If both refer to the same reference they are equal. 
    if(ReferenceEquals(obj, this)) 
    return true; 

    // If the other object is null they are not equal because in C# this cannot be null. 
    if(ReferenceEquals(obj, null)) 
    return false; 

    // Compare data to evaluate equality  
    return _data.Equals(obj._data); 
} 

public override bool Equals(object obj) 
{ 
    // If both refer to the same reference they are equal. 
    if(ReferenceEquals(obj, this)) 
    return true; 

    // If the other object is null or is of a different types the objects are not equal. 
    if(ReferenceEquals(obj, null) || obj.GetType() != GetType()) 
    return false; 

    // Use type-safe equality comparison 
    return Equals((MyClass)obj); 
} 

public override int GetHashCode() 
{ 
    // Use data's hash code as our hashcode 
    return _data.GetHashCode(); 
} 

我認爲,這涵蓋了所有角落(繼承和這樣的)案件,但我可能是錯的。你們有什麼感想?

回答

4

我寫了一個相當全面的指南,這一段時間回來。一開始你的equals實現應該是共享的(即,一個對象應該通過一個強類型對象的過載)。另外你需要考慮一些事情,比如你的對象應該是不可變的,因爲需要重寫GetHashCode。這裏更多的信息:

http://gregbeech.com/blog/implementing-object-equality-in-dotnet

0

關於繼承,我認爲你應該讓OO範式發揮它的魔力。

具體來說,應該刪除GetType()檢查,它可能會破壞多態性。

0

我同意chakrit,如果不同類型的對象具有相同的數據或ID,則應允許它們在語義上相同。

就個人而言,我使用以下命令:

public override bool Equals(object obj) 
    { 
     var other = obj as MyClass; 
     if (other == null) return false; 

     return this.data.Equals(other.data); 
    } 
1

更好的希望,如果它也是一個引用類型this._data不爲空。

public bool Equals(MyClass obj) 
{ 
    if (obj == null) { 
     return false; 
    } 
    else { 
     return (this._data != null && this._data.Equals(obj._data)) 
         || obj._data == null; 
    } 
} 

public override bool Equals(object obj) 
{ 
    if (obj == null || !(obj is MyClass)) { 
     return false; 
    } 
    else { 
     return this.Equals((MyClass)obj); 
    } 
} 

public override int GetHashCode() { 
    return this._data == null ? 0 : this._data.GetHashCode(); 
} 
相關問題