字典键有字符限制吗?
在 .NET 中我可以使用任何字符串作为字典键吗? 这是模板引擎的一部分,我计划允许用户添加他们的自定义标头和值。
标题将类似于“X 的值”或“分析和 XYZ 报告摘要”,我担心他们是否会在罕见字符或类似内容中遇到异常。
我假设存在大小限制,但希望它大于 256 个字符。 MSDN 尚未提供有关该主题的任何详细信息。
In .NET can I use any string as a dictionary key? This is part of a templating engine and I'm planning allow users to add their custom headers and values.
Headers will be something like "Value of X" or "Summary of Analyse & XYZ Reports", I'm worried if they would get an exception in a rare character or something like that.
I assume there size limit but expecting it to be larger than 256 characters. MSDN hasn't got any details on the subject.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
字典对用作其键和值的类型没有任何特殊知识。 无论对象类型如何,它都会简单地调用
GetHashCode
和Equals
方法,以允许它将值放入正确的存储桶中并再次检索它。 这意味着任何正确实现这些方法的类都可以用作密钥。string
类确实根据其值正确实现了这些方法,因此只要您可以构造字符串的实例,就可以将其用作键。The dictionary doesn't have any special knowledge of the types used as its keys and values. Irrespective of the object type it will simply call the
GetHashCode
andEquals
methods to allow it to put the value in the right bucket and retrieve it again. Which means that any class which correctly implements these methods can be used as the key.The
string
class does correctly implement these methods based on its value, so as long as you can construct an instance of the string, then you can use it as the key.是的,它可以使用任何有效的字符串(仅限数十亿字节)。
顺便说一句,您可以传递一个自定义的
IEqualityComparer
,您可以将其传递给可能需要最大限制的Dictionary
构造函数。Yes, it can use any valid string (which is limited to a couple billion bytes).
BTW, you might pass a custom
IEqualityComparer<T>
that you might pass to theDictionary
constructor which might require a maximum limit.由于密钥只是一个 .NET 字符串,请参阅此相关的问题:.NET 字符串的最大可能长度是多少?
Since the key is just a .NET string, see this related SO question: What is the maximum possible length of a .NET string?