Is there any character limitation in Dictionary Keys?

血红的双手。 提交于 2019-12-10 09:28:05

问题


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.


回答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.




回答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.

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?



来源:https://stackoverflow.com/questions/874285/is-there-any-character-limitation-in-dictionary-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!