在C#中,KeyValuePair是一个用于存储键值对的无序集合。它位于System.Collections.Generic命名空间中。要使用KeyValuePair,首先需要创建一个KeyValuePair对象,然后将其添加到集合中,例如List或Dictionary。
以下是如何在C#中使用KeyValuePair的示例:
using System;
using System.Collections.Generic;
List<KeyValuePair<string, int>> myKeyValuePairList = new List<KeyValuePair<string, int>>();
myKeyValuePairList.Add(new KeyValuePair<string, int>("apple", 1));
myKeyValuePairList.Add(new KeyValuePair<string, int>("banana", 2));
myKeyValuePairList.Add(new KeyValuePair<string, int>("orange", 3));
foreach (KeyValuePair<string, int> kvp in myKeyValuePairList)
{
Console.WriteLine("Key: " + kvp.Key + ", Value: " + kvp.Value);
}
Dictionary<string, int> myKeyValuePairDictionary = new Dictionary<string, int>();
myKeyValuePairDictionary.Add(new KeyValuePair<string, int>("apple", 1));
myKeyValuePairDictionary.Add(new KeyValuePair<string, int>("banana", 2));
myKeyValuePairDictionary.Add(new KeyValuePair<string, int>("orange", 3));
foreach (KeyValuePair<string, int> kvp in myKeyValuePairDictionary)
{
Console.WriteLine("Key: " + kvp.Key + ", Value: " + kvp.Value);
}
这就是在C#中使用KeyValuePair的基本方法。您可以根据需要创建和使用自己的键值对集合。