GetHashCode functionality

本文关键字:functionality GetHashCode | 更新日期: 2023-09-27 18:37:28

为什么两个对象的哈希代码不相同,即使它们具有相似的值。在对象之间找到值相等的另一种最佳方法是什么,而无需读取每个属性并与其他属性进行检查?

                Person person = new Person();
                person.Name = "X";
                person.Age = 25;
                person.Zip = 600056;
                person.Sex = 'M';
                Person person1 = new Person();
                person1.Name = "X";
                person1.Age = 25;
                person1.Zip = 600056;
                person1.Sex = 'M';

                int hashCode1 = person1.Name.GetHashCode();
                int hashCode = person.Name.GetHashCode();
                // hashCode1 and hashCode values are same.
                if (person.GetHashCode() == person1.GetHashCode())
                {
                    // Condition is not satisfied
                }

GetHashCode functionality

在你的

代码中 hashCode1 == hashCode 是真的,因为散列相同的字符串将始终给你相同的结果。 但是,insances是不同的,因此您必须以适合您的业务逻辑的方式覆盖GetHashCode()

    public override int GetHashCode()
    {
        return Name.GetHashCode() ^ Zip.GetHashCode() ^ Sex ^ Age;
    }

我建议你看看这个答案 C# 中的 GetHashCode 指南。

和 http://musingmarc.blogspot.com/2007/08/vtos-rtos-and-gethashcode-oh-my.html

在您的示例中,两个对象相似但不相同。它们是不同的实例,因此它们具有不同的哈希代码。还有人 1 == 人 2 和人 1。等于(人 2) 为假。

您可以覆盖此行为。如果认为这两个对象相同(如果这些属性相等),则可以:

public override bool Equals(object other) {
    if(other == this) return true;
    var person = other as Person;
    if(person == null) return false;
    return person.Name == Name && person.Age == Age && person.Zip == Zip && person.Sex == Sex;

}

public override int GetHashCode() {
    //some logic to create the Hash Code based on the properties. i.e.
    return (Name + Age + Zip + Sex).GetHashCode(); // this is just a bad example!
}

为什么两个对象的哈希代码不相同,即使它们具有相似的值

因为这是唯一识别它们的预期方式。AFAIK,默认情况下,大多数框架/库都使用指针值。

在对象之间找到值相等的另一种最佳方法是什么,而无需读取每个属性并与其他属性进行检查?

根据您的需要,取决于使它们"平等"的原因。基本上它仍然是比较属性,但可能只是更有限。