使用 IEquatable 的好处

Jay*_*y1b 1 c# interface

我一直在研究 IEqualityComparer 和 IEquitable。

来自诸如IEqualityComparer<T> 和 IEquatable<T> 之间有什么区别?两者之间的区别现在很明显了。“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;
    }

}
Run Code Online (Sandbox Code Playgroud)

我的问题是为什么我要使用它?对于下面的简单版本来说,似乎有很多额外的代码(bool o):

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

    bool o = personOne.Id == personTwo.Id;
Run Code Online (Sandbox Code Playgroud)

小智 5

IEquatable<T>由泛型集合用来确定相等性。

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

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

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