.net 3.5 List<T> Equality and GetHashCode

狂风中的少年 提交于 2020-01-03 18:20:23

问题


I'm implementing IEquatable in a custom class that has a List<T> as a property, like so:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public List<string> Dislikes;

    public bool Equals(Person p)
    {
        if (p == null)
        {
            return false;
        }
        if (object.ReferenceEquals(this, p))
        {
            return true;
        }

        return this.FirstName == p.FirstName 
            && this.LastName == p.LastName
            && this.Dislikes == p.Dislikes; //or this.Dislikes.Equals(p.Dislikes)
    }

    public override int GetHashCode()
    {
        int hash = 17;
        hash = hash * 23 + (this.FirstName ?? String.Empty).GetHashCode();
        hash = hash * 23 + (this.LastName ?? String.Empty).GetHashCode();
        hash = hash * 23 + this.Dislikes.GetHashCode();
        return hash;
    }
}

I'm concerned about the List while trying to implement the Equals and GetHashCode methods. Specifically, will List<T>.Equals evaluate the equality of it's contents? Likewise for List<T>.GetHashCode?


回答1:


Nope .Equals will just do a Reference comparison and GetHashCode will return the standard code allocated per object.

If you want to perform .Equals base on the content of the list you'll have to enumerate over it yourself, like wise with generating a hash code.



来源:https://stackoverflow.com/questions/2068226/net-3-5-listt-equality-and-gethashcode

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!