字典键中是否有字符限制?

时间:2022-09-06 22:17:03

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.

在.NET中我可以使用任何字符串作为字典键吗?这是模板引擎的一部分,我计划允许用户添加自定义标头和值。

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.

标题将类似于“X的价值”或“分析和XYZ报告的摘要”,我担心如果他们会在罕见的角色或类似的东西中获得例外。

I assume there size limit but expecting it to be larger than 256 characters. MSDN hasn't got any details on the subject.

我假设有大小限制,但期望它大于256个字符。 MSDN没有关于这个问题的任何细节。

3 个解决方案

#1


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 the Dictionary constructor which might require a maximum limit.

顺便说一句,您可能会传递一个自定义的IEqualityComparer ,您可能会将其传递给可能需要最大限制的Dictionary构造函数。

#2


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 and Equals 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.

字典对用作其键和值的类型没有任何特殊知识。无论对象类型如何,它都会简单地调用GetHashCode和Equals方法,以允许它将值放入正确的存储桶中并再次检索它。这意味着任何正确实现这些方法的类都可以用作键。

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.

字符串类根据其值正确实现这些方法,因此只要您可以构造字符串的实例,就可以将其用作键。

#3


Since the key is just a .NET string, see this related SO question: What is the maximum possible length of a .NET string?

由于密钥只是一个.NET字符串,请参阅此相关的SO问题:.NET字符串的最大可能长度是多少?

#1


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 the Dictionary constructor which might require a maximum limit.

顺便说一句,您可能会传递一个自定义的IEqualityComparer ,您可能会将其传递给可能需要最大限制的Dictionary构造函数。

#2


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 and Equals 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.

字典对用作其键和值的类型没有任何特殊知识。无论对象类型如何,它都会简单地调用GetHashCode和Equals方法,以允许它将值放入正确的存储桶中并再次检索它。这意味着任何正确实现这些方法的类都可以用作键。

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.

字符串类根据其值正确实现这些方法,因此只要您可以构造字符串的实例,就可以将其用作键。

#3


Since the key is just a .NET string, see this related SO question: What is the maximum possible length of a .NET string?

由于密钥只是一个.NET字符串,请参阅此相关的SO问题:.NET字符串的最大可能长度是多少?