c# keyvaluepair怎样存储
在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>
,然后向其中添加了三个键值对。我们还展示了如何访问、更新和删除字典中的键值对,以及如何检查字典中是否存在某个键。