中級 › The given key was not present in the dictionary の原因と直し方 › パターン2
The given key was not present in the dictionary の原因と直し方
Dictionaryに登録されていないキーをインデクサで読み取ろうとすると発生します。
1 class Program { 2 static void Main(string[] args) { 3 var names = new System.Collections.Generic.Dictionary<int, string>(); 4 names[1] = "Taro"; 5 System.Console.WriteLine(names[__]); ^ 6 } 7 }
Unhandled exception. System.Collections.Generic.KeyNotFoundException: The given key '2' was not present in the dictionary.
at Program.Main(String[] args) in Program.cs:line 5
空欄を埋めてビルドを通す
キーの型が数値でも規則は同じです。登録していない番号を指定すると例外になります。
次の問題