What are the differences b/w Hashtable, Dictionary and KeyValuePair?
我在代码中使用字典,但我的同事使用哈希表。msdn说他们致力于密钥-值对。hashtable和dictionary的示例在msdn上是相同的。
那么,他们之间有多大的不同?哪一个是最好的,还是适合不同的场合?
现在,您唯一应该看到
键值对包含一个键和一个值。字典或哈希表包含许多键到其关联值的映射。
当您希望将两个相关信息作为一个单元存储时,
字典是一个类型化的哈希表。如果知道键和值的数据类型,出于性能原因使用字典(避免强制转换)。
以下是一些示例用法:
1 2 3 4 5 6 7 8 9 10 11 | var dict = new Dictionary<string, int>(); dict.Add("Hello", 1); foreach (KeyValuePair<string, int> entry in dict) { string s = entry.Key; int i = entry.Value; // More logic here } |
一个主要区别是
文件上说:
Hashtable is thread safe for use by multiple reader threads and a single writing thread. It is thread safe for multi-thread use when only one of the threads perform write (update) operations, which allows for lock-free reads provided that the writers are serialized to theHashtable . To support multiple writers all operations on theHashtable must be done through the wrapper returned by theSynchronized method, provided that there are no threads reading the Hashtable object.
号
与
A
Dictionary(Of TKey, TValue) can support multiple readers concurrently, as long as the collection is not modified.
号