C#中的KeyValuePair類(lèi)主要用于表示鍵值對(duì)(Key-Value Pair)數(shù)據(jù)結(jié)構(gòu)。它是一個(gè)泛型類(lèi),可以存儲(chǔ)任何類(lèi)型的鍵和值。KeyValuePair在許多場(chǎng)景中都非常有用,例如在字典、哈希表、集合和配置文件等地方。
以下是KeyValuePair類(lèi)的一些常見(jiàn)用途:
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];
}
}