Why is Dictionary preferred over Hashtable in C#?(为什么字典在 C# 中优于 Hashtable?)
问题描述
在大多数编程语言中,字典比哈希表更受欢迎.背后的原因是什么?
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<TKey, TValue> 获得类型安全,因为您不能将任何随机对象插入其中,并且您不必强制转换取出的值.
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
来源
这篇关于为什么字典在 C# 中优于 Hashtable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么字典在 C# 中优于 Hashtable?
基础教程推荐
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 将数据集转换为列表 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 如果条件可以为空 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
