为什么在 C# 中字典优先于哈希表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/301371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why is Dictionary preferred over Hashtable in C#?
提问by Nakul Chaudhary
In most programming languages, dictionaries are preferred over hashtables. What are the reasons behind that?
在大多数编程语言中,字典比哈希表更受欢迎。这背后的原因是什么?
采纳答案by Michael Madsen
For what it's worth, a Dictionary is(conceptually) a hash table.
就其价值而言,字典是(概念上)一个哈希表。
If you meant "why do we use the Dictionary<TKey, TValue>
class instead of the Hashtable
class?", then it's an easy answer: Dictionary<TKey, TValue>
is a generic type, Hashtable
is not. That means you get type safety with Dictionary<TKey, TValue>
, because you can't insert any random object into it, and you don't have to cast the values you take out.
如果您的意思是“为什么我们使用Dictionary<TKey, TValue>
类而不是Hashtable
类?”,那么答案很简单:Dictionary<TKey, TValue>
是泛型类型,Hashtable
不是。这意味着您可以使用 获得类型安全Dictionary<TKey, TValue>
,因为您不能将任何随机对象插入其中,并且您不必强制转换您取出的值。
Interestingly, the Dictionary<TKey, TValue>
implementation in the .NET Framework is based on the Hashtable
, as you can tell from this comment in its source code:
有趣的是,Dictionary<TKey, TValue>
.NET Framework 中的实现基于Hashtable
,正如您从其源代码中的此注释中可以看出的:
The generic Dictionary was copied from Hashtable's source
通用字典是从 Hashtable 的源中复制的
回答by gius
Because Dictionary
is a generic class ( Dictionary<TKey, TValue>
), so that accessing its content is type-safe (i.e. you do not need to cast from Object
, as you do with a Hashtable
).
因为Dictionary
是一个泛型类 ( Dictionary<TKey, TValue>
),所以访问它的内容是类型安全的(即您不需要Object
像使用 a 那样从 强制转换Hashtable
)。
Compare
相比
var customers = new Dictionary<string, Customer>();
...
Customer customer = customers["Ali G"];
to
到
var customers = new Hashtable();
...
Customer customer = customers["Ali G"] as Customer;
However, Dictionary
is implemented as hash table internally, so technically it works the same way.
但是,Dictionary
在内部实现为哈希表,因此从技术上讲,它的工作方式相同。
回答by Marc Gravell
In .NET, the difference between Dictionary<,>
and HashTable
is primarily that the former is a generic type, so you get all the benefits of generics in terms of static type checking (and reduced boxing, but this isn't as big as people tend to think in terms of performance - there is a definite memory cost to boxing, though).
在.NET之间的差异Dictionary<,>
,并HashTable
主要是前者是一个泛型类型,所以你在静态类型检查(并降低拳击而言仿制药的所有好处,但这不是大如人们往往认为在性能方面——不过,拳击有一定的内存成本)。
回答by flesh
The Hashtable
is a loosely-typed data structure, so you can add keys and values of any type to the Hashtable
. The Dictionary
class is a type-safe Hashtable
implementation, and the keys and values are strongly typed. When creating a Dictionary
instance, you must specify the data types for both the key and value.
该Hashtable
是弱类型的数据结构,这样你就可以添加任何类型的的密钥和值Hashtable
。该Dictionary
班是一种安全的Hashtable
实现和键和值是强类型。创建Dictionary
实例时,您必须为键和值指定数据类型。
回答by user38902
FYI: In .NET, Hashtable
is thread safe for use by multiple reader threads and a single writing thread, while in Dictionary
public static members are thread safe, but any instance members are not guaranteed to be thread safe.
仅供参考:在 .NET 中,供Hashtable
多个读取器线程和单个写入线程使用是线程安全的,而在Dictionary
公共静态成员中是线程安全的,但不保证任何实例成员都是线程安全的。
We had to change all our Dictionaries back to Hashtable
because of this.
因此,我们不得不将所有词典改回Hashtable
。
回答by rix0rrr
People are saying that a Dictionary is the same as a hash table.
人们说字典与哈希表相同。
This is not necessarily true. A hash table is one way to implementa dictionary. A typical one at that, and it may be the default one in .NET in the Dictionary
class, but it's not by definition the only one.
这不一定是真的。哈希表是实现字典的一种方式。一个典型的,它可能是Dictionary
类中 .NET 中的默认一个,但它不是唯一的定义。
You could equally well implement a dictionary using a linked list or a search tree, it just wouldn't be as efficient (for some metric of efficient).
您同样可以使用链表或搜索树来实现字典,但效率不会那么高(对于某些效率指标)。
回答by rix0rrr
One more difference that I can figure out is:
我能弄清楚的另一个区别是:
We can not use Dictionary<KT,VT> (generics) with web services. The reason is no web service standard supports the generics standard.
我们不能在 Web 服务中使用 Dictionary<KT,VT>(泛型)。原因是没有 Web 服务标准支持泛型标准。
回答by Brant
Notice that MSDN says: "Dictionary<(Of <(TKey, TValue>)>) class is implemented as a hash table", not "Dictionary<(Of <(TKey, TValue>)>) class is implemented as a HashTable"
请注意,MSDN 说:“Dictionary<(Of <(TKey, TValue>)>) 类实现为哈希表”,而不是“Dictionary<(Of <(TKey, TValue>)>) 类实现为HashTable”
Dictionary is NOT implemented as a HashTable, but it is implemented following the concept of a hash table. The implementation is unrelated to the HashTable class because of the use of Generics, although internally Microsoft could have used the same code and replaced the symbols of type Object with TKey and TValue.
Dictionary 不是作为 HashTable 实现的,而是按照哈希表的概念实现的。由于使用了泛型,该实现与 HashTable 类无关,尽管在内部 Microsoft 可以使用相同的代码并将 Object 类型的符号替换为 TKey 和 TValue。
In .NET 1.0 Generics did not exist; this is where the HashTable and ArrayList originally began.
在 .NET 1.0 中,泛型不存在;这是 HashTable 和 ArrayList 最初开始的地方。
回答by Brant
According to what I see by using .NET Reflector:
根据我使用.NET Reflector 所看到的:
[Serializable, ComVisible(true)]
public abstract class DictionaryBase : IDictionary, ICollection, IEnumerable
{
// Fields
private Hashtable hashtable;
// Methods
protected DictionaryBase();
public void Clear();
.
.
.
}
Take note of these lines
// Fields
private Hashtable hashtable;
So we can be sure that DictionaryBase uses a HashTable internally.
所以我们可以确定 DictionaryBase 在内部使用了一个 HashTable。
回答by Marcel Toth
Dictionary
<<<>>> Hashtable
differences:
Dictionary
<<<>>>Hashtable
区别:
- Generic<<<>>> Non-Generic
- Needs own thread synchronization<<<>>> Offers thread safeversion through
Synchronized()
method - Enumerated item:
KeyValuePair
<<<>>> Enumerated item:DictionaryEntry
- Newer (> .NET 2.0) <<<>>> Older (since .NET 1.0)
- is in System.Collections.Generic<<<>>> is in System.Collections
- Request to non-existing key throws exception<<<>>> Request to non-existing key returns null
- potentially a bit faster for value types<<<>>> bit slower(needs boxing/unboxing) for value types
- 通用<<<>>> 非通用
- 需要自己的线程同步<<<>>>通过方法提供线程安全版本
Synchronized()
- 枚举项:
KeyValuePair
<<<>>> 枚举项:DictionaryEntry
- 较新 (> .NET 2.0) <<<>>> 较旧(自.NET 1.0 起)
- 在System.Collections.Generic<<<>>> 在System.Collections
- 对不存在的键的请求抛出异常<<<>>> 对不存在的键的请求返回空
- 对于值类型<<<>>>值类型可能会快一点(需要装箱/拆箱)
Dictionary
/ Hashtable
similarities:
Dictionary
/Hashtable
相似之处:
- Both are internally hashtables== fast access to many-item data according to key
- Both need immutable and unique keys
- Keys of both need own
GetHashCode()
method
- 两者都是内部哈希表== 根据键快速访问多项目数据
- 两者都需要不可变的和唯一的键
- 两者的键都需要自己的
GetHashCode()
方法
Similar.NET collections (candidates to use instead of Dictionary and Hashtable):
类似的.NET 集合(用于替代 Dictionary 和 Hashtable 的候选对象):
ConcurrentDictionary
- thread safe(can be safely accessed from several threads concurrently)HybridDictionary
- optimized performance(for few items and also for many items)OrderedDictionary
- values can be accessed via int index(by order in which items were added)SortedDictionary
- items automatically sortedStringDictionary
- strongly typed and optimized for strings
ConcurrentDictionary
-线程安全(可以从多个线程同时安全访问)HybridDictionary
-优化性能(适用于少数项目和许多项目)OrderedDictionary
- 可以通过 int 索引访问值(按添加项目的顺序)SortedDictionary
- 项目自动排序StringDictionary
- 强类型并针对字符串进行了优化