2008年9月24日水曜日

C# Dictionaryの使い方

//
Dictionary openWith = new Dictionary();

// Dictionaryに要素を追加する。
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("rtf", "wordpad.exe");

// もしも新しいキーがDictionaryに存在していたら、Addメソッドは例外を投げる
try
{
    openWith.Add("txt", "winword.exe");

}catch (ArgumentException)
{
    Console.WriteLine("An element with Key = \"txt\" already exists.");
}

// キーが存在していても、上書きが出来る。
openWith["rtf"] = "winword.exe";

// 存在していないキーを指定したら、例外が発生する。
try
{

openWith["tif"];

}catch(KeyNotFoundException)
{
}

0 件のコメント: