この記事は会員限定です。会員登録(無料)すると全てご覧いただけます。
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");
このように、基本的には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"}
};
}
このような、コレクションに追加する要素を列挙する記述は「コレクション初期化子」(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キーワードが利用できるのはローカル変数宣言時のみである。
カテゴリ:C# 3.0 処理対象:言語構文
カテゴリ:クラス・ライブラリ 処理対象:コレクション
使用ライブラリ:Dictionaryクラス(System.Collections.Generic名前空間)
使用ライブラリ:IEnumerableインターフェイス(System.Collections名前空間)
関連TIPS:ハッシュテーブル(連想配列)を使うには?(Dictionaryクラス編)
Copyright© Digital Advantage Corp. All Rights Reserved.