使用IEquatable

时间:2016-06-09 16:21:59

标签: c# interface

我一直在研究IEqualityComparer和IEquitable。

What is the difference between IEqualityComparer<T> and IEquatable<T>?这样的帖子中,两者之间的差异现在已经很明显了。 &#34; IEqualityComparer是一个对象的接口,它对两个T类型的对象进行比较。&#34;

遵循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;

1 个答案:

答案 0 :(得分:3)

泛型集合使用

IEquatable<T>来确定相等性。

来自这篇msdn文章https://msdn.microsoft.com/en-us/library/ms131187.aspx

  

在Contains,IndexOf,LastIndexOf和Remove等方法中测试相等性时,IEquatable接口由泛型集合对象(如Dictionary,List和LinkedList)使用。它应该针对可能存储在泛型集合中的任何对象实现。

这在使用结构时提供了额外的好处,因为调用IEquatable<T> equals方法不会像调用基类object等于方法那样对结构进行包装。