小编sae*_*off的帖子

使用Dictionary和HashSet的GetHashCode方法

我有一个关于Dictionary和HashSet如何在C#中工作的问题.根据我的理解,GetHashCode用于哈希表以确定密钥唯一性.

在以下MSDN页面上,它指出:

哈希码是一个数值,用于插入和标识基于散列的集合中的对象,例如Dictionary类,Hashtable类或从DictionaryBase类派生的类型.

链接: MSDN Object.GetHashCode

如果是这种情况,为什么当包含与car1相同的哈希码时,ContainsKey和Contains会为car2返回false?如果我的理解是正确的,如果MSDN说的是正确的,那么两个都不应该返回真的吗?

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


        // …
Run Code Online (Sandbox Code Playgroud)

.net c# dictionary hashset

2
推荐指数
1
解决办法
1530
查看次数

标签 统计

.net ×1

c# ×1

dictionary ×1

hashset ×1