处理一个KeyNotFoundException的最佳方式 [英] Best way to handle a KeyNotFoundException
本文介绍了处理一个KeyNotFoundException的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用的字典执行查找一个程序我工作。我在字典上运行一串钥匙,我希望某些键没有值。我赶上 KeyNotFoundException
右的地方出现,并吸收它。所有其他异常将传播到顶部。这是处理最好的方法?或者我应该使用不同的查找?该字典使用一个int作为它的键,和自定义类作为其值
I am using a dictionary to perform lookups for a program I am working on. I run a bunch of keys through the dictionary, and I expect some keys to not have a value. I catch the KeyNotFoundException
right where it occurs, and absorb it. All other exceptions will propagate to the top. Is this the best way to handle this? Or should I use a different lookup? The dictionary uses an int as its key, and a custom class as its value.
推荐答案
使用的 Dictionary.TryGetValue
来代替:
Use Dictionary.TryGetValue
instead:
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);
}
这篇关于处理一个KeyNotFoundException的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文