为什么在 C# 中字典优先于哈希表?

问题描述:

在大多数编程语言中,字典比哈希表更受欢迎.这背后的原因是什么?

In most programming languages, dictionaries are preferred over hashtables. What are the reasons behind that?

就其价值而言,字典(概念上)一个哈希表.

For what it's worth, a Dictionary is (conceptually) a hash table.

如果您的意思是为什么我们使用 Dictionary 类而不是 Hashtable 类?",那么答案很简单:Dictionary 是泛型类型,Hashtable 不是.这意味着您可以使用 Dictionary 获得类型安全性,因为您不能将任何随机对象插入其中,并且您不必强制转换您取出的值.

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.

有趣的是,.NET Framework 中的 Dictionary 实现是基于 Hashtable 的,从其源代码中的此注释可以看出:

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:

通用字典是从 Hashtable 的源代码中复制的

The generic Dictionary was copied from Hashtable's source

来源