簡體   English   中英

.NET中的KeyValuePair和Hashtable有什么區別?

[英]What is the difference between KeyValuePair and Hashtable in .NET?

我想將我的自定義集合存儲為Key,Value也是字符串List的集合。我可以使用KeyvaluePair和hashtable來實現這一點。什么是最合適的匹配,這使我在靈活性方面更具優勢?

Hashtable是隨機訪問,內部使用System.Collections.DictionaryEntry作為.NET 1.1的項目; 而.NET 2.0中的強類型System.Collections.Generic.Dictionary使用System.Collections.Generic。 KeyValuePair項目也是隨機訪問。

(注意:在提供示例時,這個答案偏向於.NET 2.0框架 - 這就是為什么它繼續使用KeyValuePair而不是DictionaryEntry - 原始問題表明這是要使用的所需類型。)

因為KeyValuePair是一個獨立的類,所以您可以手動創建KeyValuePair實例的List或Array,但是將依次訪問列表或數組。 這與Hashtable或Dictionary形成對比,Hashtable或Dictionary在內部創建自己的元素實例並隨機訪問。 兩者都是使用KeyValuePair實例的有效方法。 另請參閱有關選擇要使用的Collection類的MSDN信息

總之 :使用一小組項目時,順序訪問速度最快,而較大的一組項目則受益於隨機訪問。

Microsoft的混合解決方案 :.NET 1.1中引入的一個有趣的專業集合是System.Collections.Specialized.HybridDictionary ,它使用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

一個相關的位是Hashtable是.Net 1.1類,而KeyValuePair是在.NET 2.0中引入的。 (隨着泛型的引入)

當C#不支持泛型時創建了Hashtable。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM