Warum wird ValueType.GetHashCode () so implementiert, wie es ist?

VonValueType.cs

**Action: Our algorithm for returning the hashcode is a little bit complex. We look 
**        for the first non-static field and get it's hashcode.  If the type has no 
**        non-static fields, we return the hashcode of the type. We can't take the
**        hashcode of a static member because if that member is of the same type as 
**        the original type, we'll end up in an infinite loop.

Das hat mich heute gebissen, als ich ein KeyValuePair als Schlüssel in einem Dictionary verwendet habe (es hat den XML-Attributnamen (enum) und den Wert (string) gespeichert) und erwartet, dass der Hashcode basierend auf all seinen Feldern berechnet wird , aber laut Implementierung wurde nur der Hauptteil berücksichtigt.

Beispiel (c / p von Linqpad):

void Main()
{
    var kvp1 = new KeyValuePair<string, string>("foo", "bar");
    var kvp2 = new KeyValuePair<string, string>("foo", "baz");

    // true
    (kvp1.GetHashCode() == kvp2.GetHashCode()).Dump();
}

Das erste nicht statische Feld, denke ich, ist das erste Feld in deklarierter Reihenfolge. Dies kann auch zu Problemen führen, wenn Sie die variable Reihenfolge in der Quelle aus irgendeinem Grund ändern und glauben, dass der Code dadurch nicht semantisch geändert wird.

Antworten auf die Frage(0)

Ihre Antwort auf die Frage