C# KeyValuePair: 键值对的使用指南
C#中的KeyValuePair是一个结构体,用于表示一个键值对。KeyValuePair包含两个成员:Key和Value,分别表示键和值。
使用KeyValuePair需要引用System.Collections.Generic命名空间。下面是KeyValuePair的基本使用方法:
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add('key1', 'value1');
dict.Add('key2', 'value2');
foreach(KeyValuePair<string, string> kvp in dict)
{
Console.WriteLine('Key: {0}, Value: {1}', kvp.Key, kvp.Value);
}
// 修改键值对
dict['key1'] = 'new value';
// 删除键值对
dict.Remove('key2');
Console.ReadLine();
}
}
在上面的例子中,我们创建了一个Dictionary对象,并添加了两个键值对。然后使用foreach循环遍历Dictionary中的每个KeyValuePair,并输出其Key和Value。
我们还展示了如何修改和删除字典中的键值对。注意,修改字典中的键值对时,可以通过索引器([])访问键值对。
原文地址: https://www.cveoy.top/t/topic/oRSw 著作权归作者所有。请勿转载和采集!