検索
連載

Dictionaryクラスを簡単に初期化するには?[C# 3.0].NET TIPS

PC用表示 関連情報
Share
Tweet
LINE
Hatena
「.NET TIPS」のインデックス

連載目次

 C# 2.0(.NET Framework 2.0に含まれるC#)以降では、ジェネリック・クラスの追加によりコレクションが非常に使いやすくなっている。その1つであるDictionaryジェネリック・クラス(System.Collections.Generic名前空間のDictionary<TKey, TValue>クラス)も利用頻度の高いクラスである。

 Dictionaryクラスは.NET Framework 1.xにあったHashTableクラスを進化させたもので、キーと値の組み合わせでデータを保持し、指定したキーからペアとなっている値を素早く取り出すことができる(参考:「TIPS:ハッシュテーブル(連想配列)を使うには?(Dictionaryクラス編)」)。

 このDictionaryクラスの初期化については、例えばリファレンス・マニュアルでは、次のようなサンプル・コードが記載されている。

Dictionary<string, string> openWith
    = new Dictionary<string, string>();

// Add some elements to the dictionary. There are no
// duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");

Dictionaryオブジェクトの初期化コード例

 このように、基本的にはAddメソッドを呼び出して、キーと値のペアを追加していく必要がある。

 これがC# 3.0では、次のようにして初期値を設定できるようになっている。

using System.Collections.Generic;

class sample
{
  Dictionary<string, string> openWith
     = new Dictionary<string, string>()
  {
    {"txt", "notepad.exe"},
    {"bmp", "paint.exe"},
    {"dib", "paint.exe"},
    {"rtf", "wordpad.exe"}
  };
}

C# 3.0におけるDictionaryオブジェクトの初期化

 このような、コレクションに追加する要素を列挙する記述は「コレクション初期化子」(Collection Initializer)と呼ばれ、IEnumerableインターフェイス(System.Collections名前空間)を実装しているクラスに対して利用可能だ。実際にはコンパイラによりAddメソッドの呼び出しに置き換えられる(詳細については「C# 3.0の概要:26.4.2 コレクション初期化子」を参照)。

 ちなみにC# 3.0では、暗黙の型を表すvarキーワードを使って、さらに次のように記述することもできる。

using System.Collections.Generic;

class sample
{
  // これはコンパイル・エラー
  private var openWith3 = new Dictionary<string, string>()
  {
    {"txt", "notepad.exe"},
    {"bmp", "paint.exe"},
    {"dib", "paint.exe"},
    {"rtf", "wordpad.exe"}
  };

  public void method()
  {
    // 記述量が最も少ない書き方
    var openWith2 = new Dictionary<string, string>()
    {
      {"txt", "notepad.exe"},
      {"bmp", "paint.exe"},
      {"dib", "paint.exe"},
      {"rtf", "wordpad.exe"}
    };
  }
}

varキーワードを使ったDictionaryクラスの記述

 ただしvarキーワードが利用できるのはローカル変数宣言時のみである。

カテゴリ:C# 3.0 処理対象:言語構文
カテゴリ:クラス・ライブラリ 処理対象:コレクション
使用ライブラリ:Dictionaryクラス(System.Collections.Generic名前空間)
使用ライブラリ:IEnumerableインターフェイス(System.Collections名前空間)
関連TIPS:ハッシュテーブル(連想配列)を使うには?(Dictionaryクラス編)

「.NET TIPS」のインデックス

.NET TIPS

Copyright© Digital Advantage Corp. All Rights Reserved.

ページトップに戻る