GetHashCode-Methode mit Dictionary und HashSet

Ich habe eine Frage zur Funktionsweise von Dictionary und HashSet in C #. Nach meinem Verständnis wird GetHashCode in Hash-Tabellen verwendet, um die Eindeutigkeit von Schlüsseln zu bestimmen.

uf der folgenden MSDN-Seite heißt es:

Ein Hash-Code ist ein numerischer Wert, der zum Einfügen und Identifizieren eines Objekts in einer Hash-basierten Auflistung verwendet wird, z. B. der Dictionary-Klasse, der Hashtable-Klasse oder eines von der DictionaryBase-Klasse abgeleiteten Typs.

Verknüpfung:MSDN Object.GetHashCode

Wenn dies der Fall ist, warum geben ContainsKey und Contains für car2 false zurück, wenn sie denselben Hashcode wie car1 haben? Wenn mein Verständnis korrekt ist und wenn das, was MSDN sagt, korrekt ist, sollten dann nicht beide true zurückgeben?

class Program
{
    static void Main(string[] args)
    {            
        // Create a Dictionary and HashSet
        Dictionary<Car, int> carDictionary = new Dictionary<Car, int>();
        HashSet<Car> carSet = new HashSet<Car>();

        // Create 3 Cars (2 generic and 1 Civic)
        Car car1 = new Car();
        Car car2 = new Car();
        Car car3 = new Civic();

        // Test hash values
        int test1 = car1.GetHashCode(); // 22008501
        int test2 = car2.GetHashCode(); // 22008501
        int test3 = car3.GetHashCode(); // 12048305


        // Add 1 generic car and 1 Civic to both Dictionary and HashSet
        carDictionary.Add(car1, 1);
        carDictionary.Add(car3, 1);
        carSet.Add(car1);
        carSet.Add(car3);

        // Why are both of these false?
        bool dictTest1 = carDictionary.ContainsKey(car2);  // false
        bool setTest1 = carSet.Contains(car2); // false

        // Testing equality makes sense
        bool testA = car1.Equals(car2); // false
        bool testB = car1.Equals(car3); // false
    }
}

class Car
{
    public override int GetHashCode()
    {
        return 22008501;
    }
}

class Civic : Car
{
    public override int GetHashCode()
    {
        return 12048305;
    }
}

Antworten auf die Frage(6)

Ihre Antwort auf die Frage