哈希表和字典之间的区别
本文关键字:区别 之间 字典 哈希表 | 更新日期: 2023-09-18 11:28:07
在 C# 中,哈希表和字典是用于存储和检索键值对的两种常用集合类型。
下面的示例演示如何创建哈希表并添加元素。
示例:创建和添加元素Hashtable numberNames = new Hashtable();
numberNames.Add(1,"One"); //adding a key/value using the Add() method
numberNames.Add(2,"Two");
numberNames.Add(3,"Three");
//The following throws run-time exception: key already added.
//numberNames.Add(3, "Three");
foreach(DictionaryEntry de in numberNames)
Console.WriteLine("Key: {0}, Value: {1}", de.Key, de.Value);
可以通过传递可以存储的键和值的类型来创建Dictionary
。
IDictionary<int, string> numberNames = new Dictionary<int, string>();
numberNames.Add(1,"One"); //adding a key/value using the Add() method
numberNames.Add(2,"Two");
numberNames.Add(3,"Three");
//The following throws run-time exception: key already added.
//numberNames.Add(3, "Three");
foreach(KeyValuePair<int, string> kvp in numberNames)
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
哈希表与字典(Hashtable vs Dictionary)
下表列出了 C# 中哈希表和字典之间的差异。
Hashtable | Dictionary |
---|---|
Hashtable 包含在 System.Collections 命名空间中。 | 字典包含在 System.Collections.Generic 命名空间中。 |
Hashtable 是一个松散类型(非泛型)集合,这意味着它存储任何数据类型的键值对。 | 字典是一个通用集合。因此,它可以存储特定数据类型的键值对。 |
哈希表是线程安全的。 | 只有公共静态成员在字典中是线程安全的。 |
如果我们尝试查找不存在的键,哈希表将返回 null。 | 如果我们尝试查找不存在的键,字典会抛出异常。 |
由于装箱-拆箱,数据检索比字典集合慢。 | 数据检索比哈希表更快,因为它是类型安全的,因此不需要装箱-拆箱。 |
建议在 C# 中使用字典而不是哈希表集合。
有关详细信息,请访问 C# 教程部分中的Hashtable或Dictionary。
本文内容总结: