.NET 3.5列表< T>平等和GetHash code [英] .net 3.5 List<T> Equality and GetHashCode

查看:144
本文介绍了.NET 3.5列表< T>平等和GetHash code的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在那有一个列表的自定义类实现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.

这篇关于.NET 3.5列表&LT; T&GT;平等和GetHash code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆