gpt4 book ai didi

c# - 处理 KeyNotFoundException 的最佳方法

转载 作者:IT王子 更新时间:2023-10-29 03:45:24 24 4
gpt4 key购买 nike

我正在使用字典来查找我正在处理的程序。我在字典中运行了一堆键,我希望有些键没有值。我 catch 了 KeyNotFoundException就在它发生的地方,吸收它。所有其他异常将传播到顶部。这是处理这个问题的最佳方法吗?或者我应该使用不同的查找?该字典使用 int 作为键,使用自定义类作为值。

最佳答案

使用Dictionary.TryGetValue相反:

Dictionary<int,string> dictionary = new Dictionary<int,string>();
int key = 0;
dictionary[key] = "Yes";

string value;
if (dictionary.TryGetValue(key, out value))
{
Console.WriteLine("Fetched value: {0}", value);
}
else
{
Console.WriteLine("No such key: {0}", key);
}

关于c# - 处理 KeyNotFoundException 的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/606636/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com