コレクション

[C#] KeyValuePairを生成する

2021年4月6日

KeyValuePair値を生成するサンプルです。

サンプル

例)KeyValuePairを生成する

using System.Collections.Generic;

//Key="1"、Value="東京都"のKeyValuePairを生成する
KeyValuePair<string, string> val
  = new KeyValuePair<string, string>("1", "東京都");

以下はよくやりがちなNG例です。

NG例)KeyValuePairを生成する ※エラーになります。

using System.Collections.Generic;

//KeyValuePairを生成する
KeyValuePair<string, string> val
  = new KeyValuePair<string, string>();

//値を設定する ※コンパイルエラーになります。
val.Key = "1";
val.Value = "東京都";

KeyValuePairはインスタンスを生成する時にしか値を設定することができないので、
上記の書き方はNGです。

備考

  • KeyValuePairは、キーと値をセットで保持するために標準で用意されたデータクラスです。
  • KeyValuePairはインスタンス生成後はreadonlyになるので値を変更することはできません。
    (newする時にしか値をセットすることができません。)

-コレクション
-