温馨提示×

c# keyvaluepair怎样存储

c#
小樊
111
2024-11-20 06:30:08
栏目: 云计算

在C#中,您可以使用KeyValuePair<TKey, TValue>结构来存储键值对。这个结构是泛型的,所以您需要指定键和值的类型。以下是一个简单的示例:

using System; using System.Collections.Generic; class Program { static void Main() { // 创建一个Dictionary<string, int>,它是一个键值对的集合 Dictionary<string, int> myDictionary = new Dictionary<string, int>(); // 添加键值对到字典中 myDictionary.Add("apple", 5); myDictionary.Add("banana", 8); myDictionary.Add("orange", 10); // 访问字典中的值 Console.WriteLine("Value of 'apple': " + myDictionary["apple"]); // 更新字典中的值 myDictionary["apple"] = 6; Console.WriteLine("Updated value of 'apple': " + myDictionary["apple"]); // 删除字典中的键值对 myDictionary.Remove("banana"); // 检查字典中是否存在某个键 if (myDictionary.ContainsKey("banana")) { Console.WriteLine("Key 'banana' exists."); } else { Console.WriteLine("Key 'banana' does not exist."); } } } 

在这个示例中,我们创建了一个Dictionary<string, int>,然后向其中添加了三个键值对。我们还展示了如何访问、更新和删除字典中的键值对,以及如何检查字典中是否存在某个键。

0