什么可以用作C#字典中的键? [英] What can you use as keys in a C# dictionary?

查看:260
本文介绍了什么可以用作C#字典中的键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自一个python世界,只有可以将哈希的对象用作字典的键。 C#有类似的限制吗?您可以使用自定义类型作为字典键吗?

解决方案

字典键的要求是可比较和可分散。这是一直在.NET中的海龟,每个类型(指针类型除外)都来自于System.Object,它的Equals()方法总是可比的。而且可以通过GetHashCode()方法进行哈希。所以任何.NET类型自动可以用作键。



如果要使用自己的类型作为键,那么只需要做一些特殊的事情,如果你想重新定义对象标识。换句话说,如果你需要两个不同的对象相等的能力。然后,您将覆盖Equals()方法,通常比较对象的字段。然后你还必须覆盖GetHashCode(),相等的对象必须生成相同的哈希码。



如果类型无法更改,或者您想要自定义Dictionary的行为,那么您可以将自定义IEqualityComparer<>传递给构造函数。请记住,您使用自己的GetHashCode()生成的哈希码的质量会确定字典的效率。


I come from a python world where only hashable objects may be used as keys to a dictionary. Is there a similar restriction in C#? Can you use custom types as dictionary keys?

解决方案

The requirement for a dictionary key is that it is comparable and hashable. That's turtles all the way down in .NET, every type (other than pointer types) derives from System.Object and it is always comparable thanks to its Equals() method. And hashable thanks to its GetHashCode() method. So any .NET type automatically can be used as a key.

If you want to use your own type as the key then you only need to do something special if you want to re-define object identity. In other words, if you need the ability for two distinct objects to be equal. You'd then override the Equals() method, typically comparing fields of the object. And then you must also override GetHashCode(), equal objects must generate the same hash code.

If the type cannot be changed or you want to customize the behavior especially for the Dictionary then you can pass a custom IEqualityComparer<> to the constructor. Keep in mind that the quality of the hash code you generate with your own GetHashCode() determines the dictionary efficiency.

这篇关于什么可以用作C#字典中的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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