2016-06-09 44 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方法将提供一个附加的好处。