以整数数组为键的字典
我需要一个字典,其键是整数数组,例如 Dictionary
或
Dictionary<List<int>,string>.
但我很惊讶 Equality 方法和哈希码方法没有为我定义。除了创建我自己的 MyType: List
并定义所有必要的方法之外,是否有任何简单的方法来实现这样的结构?
I need a Dictionary whose key is an array of integers for example Dictionary<int[],string>
or
Dictionary<List<int>,string>.
But I am quite surprised that the Equality method and hash code method is not defined for me. Is there any easy way to implement such a structure other than creating my own MyType: List<int>
and to define all necessary methods?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它不是预定义的,因为它昂贵。如果您知道您的列表很短,那么只需实施明显的覆盖即可。如果没有,您将必须至少为 GetHashCode 想出某种启发式方法。比如说,仅将前几个元素的 GetHashCode 与长度一起进行异或运算。
It isn't predefined because it is expensive. If you know your list is short then just implement the obvious overrides. If not, you'll have to come up with some kind of heuristic for at least GetHashCode. Say, GetHashCode of only the first couple of elements xor-ed together with the Length.
创建自己的类型。
您可以在某处提供两个方法并使用
Dictionary
代替Instead of creating your own type, you could provide two methods somewhere
and use a
Dictionary<string,string>
instead.GetHashCode 和 Equality 是为 List 定义的,它们只是不会被重写以提供您可能期望的行为。
如果您使用的是 .NET 3.5,则可以为 List 编写扩展方法,以实现
GetHashCode()
和Equality()
的重写GetHashCode and Equality are defined for List, they're just not overridden to give you behavior that you might expect and instead.
If you're using .NET 3.5 you can write a extension methods for List that implements an override for both
GetHashCode()
, andEquality()