C#のKeyValuePairの使い方
C#では、KeyValuePair<TKey, TValue>はキーバリューペアを表す構造体です。キーと値を表すKeyとValueという2つのプロパティを持ちます。
KeyValuePair<TKey, TValue>の一般的な用途を以下に示します。
- KeyValuePair<TKey, TValue>オブジェクトを作成する:
KeyValuePair<string, int> pair = new KeyValuePair<string, int>("Key", 123);
- キーと値を取得する:
string key = pair.Key;
int value = pair.Value;
- 更新キーと値を更新する:
pair = new KeyValuePair<string, int>("NewKey", 456);
- KeyValuePair<TKey, TValue>型をパラメーターまたは戻り値として使用:
public KeyValuePair<string, int> GetKeyValuePair()
{
return new KeyValuePair<string, int>("Key", 123);
}
public void ProcessKeyValuePair(KeyValuePair<string, int> pair)
{
// 处理键值对
}
- KeyValuePair<TKey, TValue>を使用して辞書内の項目を反復処理する:
Dictionary<string, int> dictionary = new Dictionary<string, int>();
// 添加键值对到字典
foreach (KeyValuePair<string, int> pair in dictionary)
{
string key = pair.Key;
int value = pair.Value;
// 处理键值对
}
KeyValuePair<TKey, TValue>は要するに、キーとバリューのペアを表すのに便利なデータ構造で、辞書内で反復したり、引数や戻り値として使用することができます。