.net 3.5列出<t> Equality和GetHashCode </t>

时间:2010-01-14 23:07:45

标签: .net list equality

我在一个自定义类中实现IEquatable,该类具有List <T>作为属性,如下所示:

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;
    }
}

我在尝试实现Equals和GetHashCode方法时关注List。具体来说,将列出<T>。等于评估其内容的相等性?同样适用于列表<T>。GetHashCode?

1 个答案:

答案 0 :(得分:11)

Nope .Equals将只进行Reference比较,GetHashCode将返回每个对象分配的标准代码。

如果你想根据列表的内容执行.Equals,你必须自己枚举它,就像生成哈希码一样明智。