簡體   English   中英

使用IEquatable的好處

[英]Benefits of using IEquatable

我一直在研究IEqualityComparer和IEquitable。

從諸如IEqualityComparer <T>和IEquatable <T>之間有什么區別的帖子 兩者之間的區別現在很明顯。 “ IEqualityComparer是一個對象的接口,該對象對兩個類型為T的對象執行比較。”

按照https://msdn.microsoft.com/zh-cn/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;
    }

}

我的問題是為什么要使用它? 下面的簡單版本(布爾o)似乎有很多額外的代碼:

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

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

通用集合使用IEquatable<T>來確定相等性。

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

當通過諸如Contains,IndexOf,LastIndexOf和Remove之類的方法測試是否相等時,IEquatable接口由Dictionary,List和LinkedList等通用集合對象使用。 應該為可能存儲在通用集合中的任何對象實現它。

這在使用結構時提供了額外的好處,因為調用IEquatable<T> equals方法不會像調用基礎object equals方法那樣對結構進行包裝。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM