我应该如何为HashSet覆盖Equals和GetHashCode? [英] How should I override Equals and GetHashCode for HashSet?

查看:91
本文介绍了我应该如何为HashSet覆盖Equals和GetHashCode?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我说我上课:

    public class Ident
    {
        public String Name { get; set; }
        public String SName { get; set; }
    }

还有一个:

    class IdenNode
    {
        public Ident id { get; set; }
        public List<IdenNode> Nodes { get; set; }

        public IdenNode()
        {
            Nodes = new List<IdenNode>();
        }
    }

我想使用HashSet<IdenNode>时要记住,当且仅当它们的id相等时,它的两个元素才是相同的.

I want to use HashSet<IdenNode> with mind that two elements of it are same(Equal) if and only if their id.Names are Equal.

所以,我要像下一个一样覆盖EqualsGetHashCode:

So, I'm gonna override Equals and GetHashCode like next:

        public override bool Equals(object obj)
        {
            IdenNode otherNode = obj as IdenNode;

            return otherNode != null && 
                   otherNode.id != null && 
                   id.Name == otherNode.id.Name;
        }

        public override int GetHashCode()
        {
            if (id != null)
                return id.Name.GetHashCode();
            else
                // what should I write here?
        }

我认为对吗?如果可以,我应该在GetHashCode中放置什么?

Am I think right? What should I place in GetHashCode if so?

更新

请告诉我可以Equals方法中使用==!=吗?还是ReferenceEquals或其他?

Could please tell me is it OK to use == and != in Equals method? Or may be ReferenceEquals or some other?

此外,我应该覆盖运算符==!=吗?

Also, should I override operators == and != ?

推荐答案

如果id(或id.Name)为null,则返回0是完全可以的.Nullable<T>(如int?)对于空"值.

If id (or id.Name) is null then it's perfectly fine to return 0. Nullable<T> (like int?) returns 0 for "null" values.

请记住,两个对象从GetHashCode()返回相同的值并不意味着相等-它仅意味着两个对象可能相等.但是,相反的情况是,两个相等"对象必须返回相同的哈希码.您对EqualsGetHashCode

Keep in mind that two objects returning the same value from GetHashCode() does NOT imply equality - it only implies that two objects might be equal. The flip, however, is that two "equal" objects must return the same hash code. Both principles seem to be fulfilled by your definition of Equals and GetHashCode

这篇关于我应该如何为HashSet覆盖Equals和GetHashCode?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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