Dictionary.ContainsKey()工作不正常 [英] Dictionary.ContainsKey() not working as expected

查看:534
本文介绍了Dictionary.ContainsKey()工作不正常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本字典。

Dictionary<YMD, object> cache = new Dictionary<YMD, object>();

的YMD类是我的发明之一,其是仅包含年,月,和日期的一类。的目的是,该数据将被编入索引经天是涉及。无论如何,我已经实现了equals()和的CompareTo()函数,还有==和!=运算符。

The YMD class is one of my inventions, it is a class containing only the year, month, and date. The purpose is that the data will be indexed by the day is relates to. Anyhow, I have implemented the Equals() and CompareTo() functions, as well as the == and != operators.

尽管如此,Dictionary.ContainsKey()函数将始终返回false,即使存在密钥。

Despite this, the Dictionary.ContainsKey() function will always return false, even if the key exists.

我马上想到我的比较函数必须被打破,但是写单元测试所有的人后,不会出现这种情况。

I immediately thought my comparison functions must be broken, but after writing unit tests for all of them it does not appear to be the case.

有一些关于字典类的,我不知道吗?

Is there something about the dictionary class that I do not know?

推荐答案

通过一本字典, GetHash code()是至关重要的。对于事情是相等的(等于()==真)它必须返回相同的数字(但它允许有冲突 - 即2项可以用巧合返回相同的号码,但不考虑平等)。

With a dictionary, GetHashCode() is critical. For things that are equal (Equals() == true) it must return the same number (but it is permitted to have collisions - i.e. two items can return the same number by coincidence but not be considered equals).

此外 - 的散列code必须不可以变化,而该项目是在字典。散列在只读值好这一点,但是可选:就是不改变它!例如,如果你等于/哈希code跨越了实体名称编号(说),那么别'T改变对象的这些属性,否则你可能永远不会再看到该记录(即使你通过在同一个实例作为键)。

Additionally - the hash-code must not change while the item is in the dictionary. Hashing on readonly values are good for this, but alternatively: just don't change it! For example, if your equals / hashcode spans an entities Name and Id (say), then don't change those properties of the object, or you may never see that record again (even if you pass in the same instance as the key).

这篇关于Dictionary.ContainsKey()工作不正常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆