2011-03-25 31 views
0

可能重複:
What's the difference between IEquatable and just overriding Object.Equals() ?Equals()IEquatable它們是如何相互關聯的?

我知道,在C#中的所有類是從對象和對象deived有一個名爲Equals()虛方法。

爲什麼我應該侮辱IEquatable?爲什麼不重寫object.Equals

+2

相同[有什麼區別IEquatable和剛剛覆蓋Object.Equals()?](http://stackoverflow.com/questions/2734914/whats-the-difference-between-iequatable-and - 只是-首要對象-等於)。 – 2011-03-25 14:28:27

回答

3

IEquatable<T>定義

bool Equals(T other) 

雖然對象的equals定義

bool Equals(object other) 

所以定義IEquatable爲你的類可以讓你做的同一類的兩個項目更容易比較,而無需進行轉換到當前類型。很多時候,你會看到人們實現IEquatable,然後覆蓋對象的equals調用IEquatable的等於:

public class SomeClass : IEquatable<SomeClass> 
{ 
    public bool Equals(SomeClass other) 
    { 
     // actual compare 
    } 

    public override bool Equals(object other) 
    { 
     // cross-call to IEquatable's equals. 
     return Equals(other as SomeClass); 
    } 
} 

此外,您可以定義其他類型之間的平等,以及。像make make分數工具IEquatable

+0

@Andrew:哈,另一隻野兔?不知道我們是否與我們祖先的任何地方有關... – 2011-03-25 15:42:21

+0

非常酷!我的中間名是邁克爾 - 小世界:) – 2011-03-27 00:14:36

+0

@Andrew:非常好! – 2011-05-11 21:45:31

相關問題