类:Dictionary
属性
属性 | 用途 |
---|
Comparer | 获取用于确定字典中的键是否相等的 IEqualityComparer。 |
Count | 获取包含在 Dictionary<TKey, TValue> 中的键/值对的数目。 |
Item | 获取或设置与指定的键相关联的值。 |
Keys | 获取包含 Dictionary<TKey, TValue> 中的键的集合。 |
Values | 获取包含 Dictionary<TKey, TValue> 中的值的集合。 |
方法
方法 | 说明 |
---|
Add | 将指定的键和值添加到字典中。 |
Clear | 从 Dictionary<TKey, TValue> 中移除所有的键和值。 |
ContainsKey | 确定 Dictionary<TKey, TValue> 是否包含指定的键。 |
ContainsValue | 确定 Dictionary<TKey, TValue> 是否包含特定值。 |
Equals(Object) | 确定指定的 Object 是否等于当前的 Object。 (继承自 Object。) |
Finalize | 允许对象在“垃圾回收”回收之前尝试释放资源并执行其他清理操作。 |
1
2 Dictionary<string, string> openWith = new Dictionary<string, string>();
3
4
5
6 openWith.Add("txt", "notepad.exe");
7 openWith.Add("bmp", "paint.exe");
8 openWith.Add("dib", "paint.exe");
9 openWith.Add("rtf", "wordpad.exe");
10
11
12
13 Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);
14
15
16
17 openWith["rtf"] = "winword.exe";
18 Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);
19
20
21
22 foreach (string key in openWith.Keys)
23 {
24 Console.WriteLine("Key = {0}", key);
25 }
26
27
28 29
30 foreach (string value in openWith.Values)
31 {
32 Console.WriteLine("value = {0}", value);
33 }
34
35
36 Dictionary<string, string>.ValueCollection valueColl = openWith.Values;
37 foreach (string s in valueColl)
38 {
39 Console.WriteLine("Second Method, Value = {0}", s);
40 }
41 42
43
44
45 foreach (KeyValuePair<string, string> kvp in openWith)
46 {
47 Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
48 }
49
50
51 52
53 try
54 {
55 openWith.Add("txt", "winword.exe");
56 }
57 catch (ArgumentException)
58 {
59 Console.WriteLine("An element with Key = \"txt\" already exists.");
60 }
61 62
63
64 65
66 openWith.Remove("doc");
67 if (!openWith.ContainsKey("doc"))
68 {
69 Console.WriteLine("Key \"doc\" is not found.");
70 }
71
73
74
75 if (openWith.ContainsKey("bmp"))
76 {
77 Console.WriteLine("An element with Key = \"bmp\" exists.");
78 }