C#中的KeyValuePair类主要用于表示键值对(Key-Value Pair)数据结构。它是一个泛型类,可以存储任何类型的键和值。KeyValuePair在许多场景中都非常有用,例如在字典、哈希表、集合和配置文件等地方。
以下是KeyValuePair类的一些常见用途:
Dictionary<string, int> myDictionary = new Dictionary<string, int>();
myDictionary.Add("apple", 1);
myDictionary.Add("banana", 2);
int value = myDictionary["apple"]; // value will be 1
var query = from kvp in myDictionary
select new { Key = kvp.Key, Value = kvp.Value };
<!-- app.config -->
<configuration>
<appSettings>
<add key="DatabaseConnectionString" value="your_connection_string_here"/>
</appSettings>
</configuration>
// C# code to read the connection string from the config file
string connectionString = ConfigurationManager.AppSettings["DatabaseConnectionString"];
public class MyClass<TKey, TValue>
{
private Dictionary<TKey, TValue> _data = new Dictionary<TKey, TValue>();
public void Add(TKey key, TValue value)
{
_data.Add(key, value);
}
public TValue Get(TKey key)
{
return _data[key];
}
}