在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
广告