.NET中KeyValuePair和Hashtable有什么区别?

8

我想将我的自定义集合存储为键,值也是字符串列表的集合。我可以使用KeyValuePair和Hashtable两种方式来实现这一目标。哪种集合更适合我,可以在灵活性方面给我更多优势?

3个回答

15

Hashtable是随机访问的,自 .NET 1.1 起在其项中使用System.Collections.DictionaryEntry;而.NET 2.0 中的强类型System.Collections.Generic.Dictionary 使用System.Collections.Generic.KeyValuePair项也是随机访问。

(注意:本答案在提供示例时偏向于.NET 2.0框架,因此继续使用KeyValuePair而非DictionaryEntry——原问题表明这是要使用的类型。)

由于KeyValuePair是独立的类,您可以手动创建一个KeyValuePair实例的列表或数组,但是列表或数组将按顺序访问。这与Hashtable或Dictionary形成对比,后两者在内部创建自己的元素实例并进行随机访问。这两种使用KeyValuePair实例的方法都是有效的。也请参阅有关选择要使用的集合类的MSDN信息

总之:当使用少量项目时,顺序访问最快,而当使用大量项目时,随机访问更为有效。

Microsoft 的混合解决方案System.Collections.Specialized.HybridDictionary 是 .NET 1.1 中引入的一种有趣的专用集合,其在集合较小时使用ListDictionary内部表示(按顺序访问),并在集合变大时自动切换到Hashtable内部表示(随机访问)。

C#示例代码

以下示例显示为不同场景创建的相同键值对实例——顺序访问(两个示例)后是一个随机访问的例子。为了简化这些示例,它们都将使用具有字符串值的int键 - 您可以替换所需使用的数据类型。

这是一个强类型的System.Collections.Generic.List键值对。
(顺序访问)

// --- Make a list of 3 Key-Value pairs (sequentially accessed) ---
// build it...
List<KeyValuePair<int, string>> listKVP = new List<KeyValuePair<int, string>>();
listKVP.Add(new KeyValuePair<int, string>(1, "one"));
listKVP.Add(new KeyValuePair<int, string>(2, "two"));
// access first element - by position...
Console.Write( "key:" + listKVP[0].Key + "value:" + listKVP[0].Value );

这里有一个键值对的 System.Array。
(顺序访问)

// --- Make an array of 3 Key-Value pairs (sequentially accessed) ---
// build it...
KeyValuePair<int, string>[] arrKVP = new KeyValuePair<int, string>[3];
arrKVP[0] = new KeyValuePair<int, string>(1, "one");
arrKVP[1] = new KeyValuePair<int, string>(2, "two");
// access first element - by position...
Console.Write("key:" + arrKVP[0].Key + "value:" + arrKVP[0].Value);

这是一组键值对的字典。
(可以进行随机访问)

// --- Make a Dictionary (strongly typed) of 3 Key-Value pairs (randomly accessed) ---
// build it ...
Dictionary<int, string> dict = new Dictionary<int, string>();
dict[1] = "one";
dict[2] = "two";
// access first element - by key...
Console.Write("key:1 value:" + dict[1]); // returns a string for key 1

3
你无法使用键值访问列表中的元素。正如此处所示,你需要迭代列表来查找所需的键。相比之下,哈希表可以让你使用键作为索引来访问值。 - jheddings
谢谢@jheddings,我添加了代码注释来指示元素是通过索引位置还是键访问的,以澄清您所说的内容。 - John K

2

其中一个相关的点是,Hashtable 是 .Net 1.1 的类,而 KeyValuePair 是在 .NET 2.0 中引入的(随着泛型的引入)。


2

在 C# 不支持泛型时,Hashtable 被创建出来。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接