.NET 3.5列表< T>平等和GetHash code平等、列表、NET、LT

2023-09-05 02:32:53 作者:八巷

我在那有一个列表的自定义类实现IEquatable < T> 作为一个属性,像这样:

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

我担心的列表,同时试图执行Equals和GetHash code的方法。具体而言,将名单&LT; T&GT; .Equals评价它的平等的内容是什么?同样,对于清单&LT; T&GT; .GetHash code

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?

推荐答案

都能跟得上.Equals将只是做一个参考比较GetHash code将返回每个对象分配的标准code。

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

如果你想对列表的内容进行.Equals基地,你得自己枚举它,就像聪明与生成一个散列code。

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.