问题描述
我刚刚看到了这种行为,对此我感到有些惊讶......
I just saw this behaviour and I'm a bit surprised by it...
如果我向字典中添加 3 或 4 个元素,然后执行For Each"以获取所有键,它们的显示顺序与我添加的顺序相同.
If I add 3 or 4 elements to a Dictionary, and then do a "For Each" to get all the keys, they appear in the same order I added them.
这让我感到惊讶的原因是 Dictionary 在内部应该是一个 HashTable,所以我希望事情以任何顺序出现(按键的散列排序,对吗?)
The reason this surprises me is that a Dictionary is supposed to be a HashTable internally, so I expected things to come out in ANY order (ordered by the hash of the key, right?)
我在这里错过了什么?这是我可以信赖的行为吗?
What am I missing here?Is this a behaviour I can count on?
好的,我已经想到了可能发生这种情况的许多原因(例如条目的单独列表,这是否是巧合等).我的问题是,有人知道这究竟是如何运作的吗?
OK, I thought already of many of the reasons why this might happen (like the separate list to entries, whether this is a coincidence, etc).My question is, does anyone know how this really works?
推荐答案
如果您在 3.5 类库上使用 .NET Reflector,您可以看到 Dictionary 的实现实际上将项目存储在一个数组中(根据需要调整大小), 并将索引散列到该数组中.获取键时,它会完全忽略哈希表并遍历项目数组.因此,您将看到您所描述的行为,因为在数组末尾添加了新项目.如果您执行以下操作,则看起来像:
If you use .NET Reflector on the 3.5 class libraries you can see that the implementation of Dictionary actually stores the items in an array (which is resized as needed), and hashes indexes into that array. When getting the keys, it completely ignores the hashtable and iterates over the array of items. For this reason, you will see the behavior you have described since new items are added at the end of the array. It looks like if you do the following:
add 1
add 2
add 3
add 4
remove 2
add 5
你会得到 1 5 3 4 因为它重用了空槽.
you will get back 1 5 3 4 because it reuses empty slots.
需要注意的是,与许多其他人一样,您不能指望在未来(或过去)的版本中出现这种行为.如果您希望对字典进行排序,则有一个 SortedDictionary 类用于这个目的.
It is important to note, like many others have, you cannot count on this behavior in future (or past) releases. If you want your dictionary to be sorted then there is a SortedDictionary class for this purpose.
这篇关于为什么条目在 .Net 词典中按顺序排列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!