要将引用类型的值用作字典键,必须做什么?
假设我有一个类 T
,我想将其用作 Dictionary
集合中的键。
我必须在 T
中实现什么,以便这些键基于 T
的值而不是 T
引用?
我希望它只是 GetHashCode()
。
Suppose I have a class T
that I want to use as a key in a Dictionary<T,U>
collection.
What must I implement in T
so that these keys are based on values of T
rather than T
references?
I'm hoping it's just GetHashCode()
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您必须实现 GetHashCode() 和 Equals()。
字典是底层的哈希表,因此您可能需要阅读以下内容: Equals/GetHashCode 的陷阱 – 哈希表如何工作?
You must implement GetHashCode() and Equals().
Dictionary is a Hashtable below the covers, so you might want to read this: Pitfalls Of Equals/GetHashCode – How Does A Hash Table Work?
如果您不在字典构造函数中传递任何
IEqualityComparer
,它将使用EqualityComparer.Default
,MSDN 定义为:因此,实现
IEquatable
将是我的选择(如果实现它,覆盖Equals
和也是有意义的无论如何,>GetHashCode
)。If you don't pass any
IEqualityComparer<T>
in the dictionary constructor, it will useEqualityComparer<T>.Default
which is defined by MSDN as :So implementing
IEquatable<T>
would be my choice (if you implement it it also makes sense to overrideEquals
andGetHashCode
anyway).要么实现
Equals
和GetHashCode
或者创建适当的IEqualityComparer
具有适合您的地图的正确形式的相等匹配。我更喜欢是有意义的……如果可以的话。 (
IEqualityComparer
路线:在许多情况下,没有一种明显正确的平等形式 - 您希望根据情况以不同的方式将对象视为平等。在这种情况下,自定义相等比较器正是您所需要的。当然,如果存在自然的相等操作,那么在类型本身中实现 IEquatableIEqualityComparer
的另一个好处是您可以为您无法控制的类型实现它。)Either implement
Equals
andGetHashCode
or create an appropriateIEqualityComparer<T>
which has the right form of equality matching for your map.I rather like the
IEqualityComparer<T>
route: in many cases there isn't one obviously-right form of equality - you want to treat objects as equal in different ways depending on the situation. In that case, a custom equality comparer is just what you need. Of course, if there is a natural equality operation, it makes sense to implementIEquatable<T>
in the type itself... if you can. (Another benefit ofIEqualityComparer<T>
is that you can implement it for types you have no control over.)您需要覆盖
Equals(object obj)
。当您修改Equals
时,始终期望您实现GetHashCode
。请阅读 MSDN 上的这篇文章。You need to override
Equals(object obj)
. It is always expected that you implementGetHashCode
when you modifyEquals
. Read this article at MSDN.