C#中的KeyNotFoundException
当您找到的键在Dictionary集合中不可用时,将引发KeyNotFoundException。
让我们看一个例子-
示例
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
try {
var dict = new Dictionary<string, string>() {
{"TV", "Electronics"},
{"Laptop", "Computers"},
};
Console.WriteLine(dict["Pen Drive"]);
}
catch (Exception e) {
Console.WriteLine(e);
}
}
}以下是输出。由于键不在字典中,因此会显示错误KeyNotFoundException错误-
输出结果
System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary. at System.Collections.Generic.Dictionary`2[TKey,TValue].get_Item (TKey key) [0x0001e] in <902ab9e386384bec9c07fa19aa938869>:0