处理KeyNotFoundException的最佳方式 [英] Best way to handle a KeyNotFoundException

查看:234
本文介绍了处理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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆