Hashtable 与 Dictionary






4.75/5 (37投票s)
Hashtable 和 Dictionary 的比较。
HashTable
Hashtable 优化了查找操作。它为每个添加的键计算一个哈希值,然后使用该哈希码快速查找元素。它是一种较旧的 .NET Framework 类型,比泛型 Dictionary
类型慢。
示例
using System.Collections;
class Program
{
static Hashtable GetHashtable()
{
// Create and return new Hashtable.
Hashtable hashtable = new Hashtable();
hashtable.Add("Area", 1000);
hashtable.Add("Perimeter", 55);
hashtable.Add("Mortgage", 540);
return hashtable;
}
public static void Main()
{
Hashtable hashtable = GetHashtable();
// See if the Hashtable contains this key.
Console.WriteLine(hashtable.ContainsKey("Perimeter"));
// Test the Contains method. It works the same way.
Console.WriteLine(hashtable.Contains("Area"));
// Get value of Area with indexer.
int value = (int)hashtable["Area"];
// Write the value of Area.
Console.WriteLine(value);
}
}
输出
True
True
1000
词典
Dictionary 用于需要快速查找的关键场景。Dictionary
类型通过键快速查找值。我们可以使用任何类型(包括 int
和 string
)的键和值。Dictionary 需要特殊的语法形式。
Dictionary 用于我们拥有许多不同元素的情况。我们指定它的键类型和值类型。它提供良好的性能。
示例
class Dict
{
static void Main()
{
// Example Dictionary again
Dictionary<string, int> d = new Dictionary<string, int>()
{
{"Lion", 2}, {"dog", 1}};
// Loop over pairs with foreach
foreach (KeyValuePair<string, int> pair in d)
{
Console.WriteLine ("{0}, {1}",pair.Key, pair.Value);
}
foreach (var pair in d)
{
Console.WriteLine("{0}, {1}", pair.Key, pair.Value);
}
Console.ReadKey();
}
}
Hashtable 和 Dictionary 之间的区别
词典
- 如果尝试查找不存在的键,它会返回错误。
- 它比 Hashtable 更快,因为没有装箱和拆箱操作。
- 只有公共静态成员是线程安全的。
- Dictionary 是一个泛型类型,这意味着我们可以将其与任何数据类型一起使用。
哈希表
- 如果尝试查找不存在的键,它会返回 null。
- 它比 Dictionary 慢,因为它需要装箱和拆箱操作。
- Hashtable 中的所有成员都是线程安全的。
- Hashtable 不是泛型类型。