2016-06-09 43 views
0

我一直在研究IEqualityComparer和IEquitable。使用IEquatable的好處

從如這樣的帖子中,兩者之間的區別現在已經很清楚了。 「IEqualityComparer是一個對象類型的接口,用於對T類型的兩個對象執行比較。」

https://msdn.microsoft.com/en-us/library/ms132151(v=vs.110).aspx爲例,IEqualityComparer的用途很簡單明瞭。

我已經按照在https://dotnetcodr.com/2015/05/05/implementing-the-iequatable-of-t-interface-for-object-equality-with-c-net/的例子來解決如何使用它,我得到了下面的代碼:

class clsIEquitable 
{ 
    public static void mainLaunch() 
    { 
     Person personOne = new Person() { Age = 6, Name = "Eva", Id = 1 }; 
     Person personTwo = new Person() { Age = 7, Name = "Eva", Id = 1 }; 

     //If Person didn't inherit from IEquatable, equals would point to different points in memory. 
     //This means this would be false as both objects are stored in different locations 

     //By using IEquatable on class it compares the objects directly 
     bool p = personOne.Equals(personTwo); 

     bool o = personOne.Id == personTwo.Id; 

     //Here is trying to compare and Object type with Person type and would return false. 
     //To ensure this works we added an overrides on the object equals method and it now works 
     object personThree = new Person() { Age = 7, Name = "Eva", Id = 1 }; 
     bool p2 = personOne.Equals(personThree); 

     Console.WriteLine("Equatable Check", p.ToString()); 

    } 
} 


public class Person : IEquatable<Person> 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public int Age { get; set; } 

    public bool Equals(Person other) 
    { 
     if (other == null) return false; 
     return Id == other.Id; 
    } 


    //These are to support creating an object and comparing it to person rather than comparing person to person 

    public override bool Equals(object obj) 
    { 
     if (obj is Person) 
     { 
      Person p = (Person)obj; 
      return Equals(p); 
     } 
     return false; 
    } 

    public override int GetHashCode() 
    { 
     return Id; 
    } 

} 

我的問題是,爲什麼我會使用它嗎?這似乎是很多額外的代碼下面的簡單版本(BOOL O):

 //By using IEquatable on class it compares the objects directly 
    bool p = personOne.Equals(personTwo); 

    bool o = personOne.Id == personTwo.Id; 
+4

*你知道你想通過Id來比較個人。存儲「Person」的任何隨機集合應該如何知道? –

+1

假設你想添加一個額外的指標來比較'Person's。然後怎樣呢?你會去尋找所有兩個'Person'進行比較並重構它們的實例,或者只是編輯Equals'實現?這是代碼重用的一個典型示例。 – EvilTak

+0

一旦它指出它就很簡單!謝謝 – Jay1b

回答

3

IEquatable<T>所使用的通用集合來確定的平等。

從這個MSDN文章https://msdn.microsoft.com/en-us/library/ms131187.aspx

的IEquatable接口被泛型集合對象,例如字典,列表和LinkedList在這樣的方法進行相等性測試時,如包含,的IndexOf,LastIndexOf和刪除。它應該用於可能存儲在通用集合中的任何對象。

此使用時結構中,由於調用IEquatable<T>等於方法不框結構體等調用基object equals方法將提供一個附加的好處。