基於雜湊表的高性能鍵值對集合,特點:
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// 1. 創建並添加元素
var openWith = new Dictionary<string, string>();
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe"); // 值可重複
openWith.Add("rtf", "Wordpad.exe");
// 2. 重複鍵異常處理
try { openWith.Add("txt", "winWord.exe"); }
catch (ArgumentException)
{ Console.WriteLine("鍵 \"txt\" 已存在。"); }
// 3. 索引器存取(獲取/修改/新增)
Console.WriteLine($"rtf = {openWith[\"rtf\"]}"); // 讀取
openWith[\"rtf\"] = \"winWord.exe\"; // 修改
openWith[\"doc\"] = \"winWord.exe\"; // 新增(鍵不存在時)
// 4. 安全嘗試獲取(避免異常)
if (openWith.TryGetValue(\"tif\", out string val))
Console.WriteLine($"tif = {val}");
else
Console.WriteLine(\"鍵 \\\"tif\\\" 不存在。\");
// 5. ContainsKey 檢查後添加
if (!openWith.ContainsKey(\"ht\"))
openWith.Add(\"ht\", \"hypertrm.exe\");
// 6. 遍歷鍵值對
foreach (var kvp in openWith)
Console.WriteLine($"Key = {kvp.Key}, Value = {kvp.Value}");
// 7. 單獨獲取值/鍵集合
foreach (string s in openWith.Values) Console.WriteLine($"Value = {s}");
foreach (string s in openWith.Keys) Console.WriteLine($"Key = {s}");
// 8. 刪除並驗證
openWith.Remove(\"doc\");
if (!openWith.ContainsKey(\"doc\"))
Console.WriteLine(\"鍵 \\\"doc\\\" 已移除。\");
Console.ReadKey();
}
}
}
| 方法/屬性 | 用途 | 異常風險 |
|---|---|---|
Add(key, value) | 添加(鍵必須唯一) | ArgumentException |
this[key] (索引器) | 讀/寫/新增 | KeyNotFoundException (讀不存在鍵) |
TryGetValue(key, out value) | 安全嘗試獲取 | 無(返回 bool) |
ContainsKey(key) | 檢查鍵存在性 | 無 |
Remove(key) | 刪除鍵值對 | 無(不存在返回 false) |
Keys / Values | 獲取鍵/值集合 | 無 |
TryGetValue,避免異常開銷capacity 減少擴容GetHashCode() 與 Equals()