GetHashCode等于C#中的类的实现 [英] GetHashCode Equals implementation for a class in C#

查看:58
本文介绍了GetHashCode等于C#中的类的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Person类,必须重写Equals和GetHashCode方法.如果名称匹配或电子邮件匹配,则两个人对象相等.使用相当有效的哈希函数来执行此操作的好方法是什么?

I have a class Person for which I have to override the Equals and GetHashCode method. Two person objects are equals if the Name matches OR if the Email matches. What's a good way of doing this with a considerably efficient hash function?

class Person
{
    string Name
    string Email

    public override Equals(object obj)
    {
        if (ReferenceEquals(obj, null))
            return false;
        if (ReferenceEquals(this, obj))
            return true;
        if (obj is Person)
        {
            Person person = (Person)obj;
            return
                (this.Name == person.Name)
                || (this.Email == person.Email);
        }
        return false;
    }

    public override GetHashCode()
    {
        // What's a good way to implement?
    }
}

推荐答案

您真的不能.好吧,除了返回常量值之外.

You can't, really. Well, not apart from returning a constant value.

以这种方式看...所有具有电子邮件"x"的人都必须具有相同的哈希码,因为它们是相等的.并且所有名称为"y"的人都必须具有相同的哈希码,因此它继续进行:

Look at it this way... all people with email "x" have to have the same hash code, because they're equal. And all people with name "y" have to have the same hash code, and so it goes on:

Name    Email    Hash
  n1       e1      h1
  n2       e1      h1 (because emails are equal
  n2       e2      h1 (because names are equal to previous)

请注意,我们如何设法将电子邮件的名称​​和更改为任意值,但哈希值仍必须为h1.

Note how we've managed to change both the name and the email to arbitrary values, but the hash has to still be h1.

这篇关于GetHashCode等于C#中的类的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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