简体   繁体   中英

Visual Studio 2017 - C# - Code Generation - GetHashCode() - Initial Value - Explanation needed

I've used the code generation feature for GetHashCode the first time. I think it is a great thing. But I don't understand the first line of code. How is the number calculated? If I add more fields to the GetHashCode algorithm (eg a field from a parent class) do I need to change this number in the first line of code?

public override int GetHashCode()
    {
        var hashCode = 589741190;
        hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(SyncKey);
        hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Name);
        hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Firstname);
        hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Lastname);
        hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Notes);
        hashCode = hashCode * -1521134295 + EqualityComparer<DateTime?>.Default.GetHashCode(Birthdate);
        return hashCode;
    }

Mostly prime numbers are used for hashing functions. However 589741190 is not a prime number. I don't know where you got the code from, but I think this number is just randomly chosen. (This does not mean that this number is bad for hashing).

There is lots of info to read here regarding this function from the official .NET repo:

https://github.com/dotnet/corefx/issues/14354

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM