C#中的Dictionary.Item []属性
C#中的Dictionary.Item[]属性用于获取或设置与Dictionary中指定键关联的值。
语法
以下是语法-
public TValue this[TKey key] { get; set; }示例
现在让我们看一个实现Dictionary.Item[]属性的示例-
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(){
Dictionary<string, string> dict =
new Dictionary<string, string>();
dict.Add("One", "Chris");
dict.Add("Two", "Steve");
dict.Add("Three", "Messi");
dict.Add("Four", "Ryan");
dict.Add("Five", "Nathan");
Console.WriteLine("Count of elements = "+dict.Count);
Console.WriteLine("\nKey/value pairs...");
foreach(KeyValuePair<string, string> res in dict){
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
Console.WriteLine("Value for key three = "+dict["Three"]);
dict["Three"] = "Ronaldo";
Console.Write("Updated value associated with key Three...");
Console.WriteLine(dict["Three"]);
if (dict.ContainsValue("Angelina"))
Console.WriteLine("\n\nValue found!");
else
Console.WriteLine("\n\nValue isn't in the dictionary!");
dict.Clear();
Console.WriteLine("Cleared Key/value pairs...");
foreach(KeyValuePair<string, string> res in dict){
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
Console.WriteLine("Count of elements now = "+dict.Count);
}
}输出结果
这将产生以下输出-
Count of elements = 5 Key/value pairs... Key = One, Value = Chris Key = Two, Value = Steve Key = Three, Value = Messi Key = Four, Value = Ryan Key = Five, Value = Nathan Value for key three = Messi Updated value associated with key Three...Ronaldo Value isn't in the dictionary! Cleared Key/value pairs... Count of elements now = 0
示例
现在让我们来看另一个实现Dictionary.Item[]方法的示例-
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(){
Dictionary<string, string> dict =
new Dictionary<string, string>();
dict.Add("One", "Chris");
dict.Add("Two", "Steve");
dict.Add("Three", "Messi");
dict.Add("Four", "Ryan");
dict.Add("Five", "Nathan");
Console.WriteLine("Count of elements = "+dict.Count);
Console.WriteLine("\nKey/value pairs...");
foreach(KeyValuePair<string, string> res in dict){
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
Console.WriteLine("Value for key three = "+dict["Three"]);
dict["Three"] = "Katie";
Console.Write("Updated value associated with key Three...");
Console.WriteLine(dict["Three"]);
}
}输出结果
这将产生以下输出-
Count of elements = 5 Key/value pairs... Key = One, Value = Chris Key = Two, Value = Steve Key = Three, Value = Messi Key = Four, Value = Ryan Key = Five, Value = Nathan Value for key three = Messi Updated value associated with key Three...Katie
热门推荐
2 修祖屋祝福语简短
10 国庆简短幽默祝福语
11 38节贺卡简短祝福语
12 简短霸气的考试祝福语
13 祝球员赛前祝福语简短
14 中考祝福语简短卡片大全
15 喜得新房文案祝福语简短
16 2026年春节祝福语简短
17 信耶稣的人祝福语简短
18 宝宝周岁可乐祝福语简短