c# - 使用字典时如何避免运行时错误

标签 c# dictionary

我有一段代码表示字典和搜索键数组。

Dictionary<string, string> items = new Dictionary<string, string>()
                                   {
                                     {"1","Blue"},
                                     {"2","Green"},
                                     {"3","White"}
                                    };

string[] keys = new[] { "1", "2", "3", "4" };

当我传递字典中不存在的键时,如何安全地避免运行时错误?

最佳答案

How to safely avoid the run time error when i pass a key that is not present in dictionary?

您还没有展示您目前是如何尝试这样做的,但是您可以使用 Dictionary<,>.TryGetValue :

foreach (string candidate in keys)
{
    string value;
    if (items.TryGetValue(candidate, out value))
    {
        Console.WriteLine("Key {0} had value {1}", candidate, value);
    }
    else
    {
        Console.WriteLine("No value for key {0}", candidate);
    }
}

关于c# - 使用字典时如何避免运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17382694/

相关文章:

c# - 将 XPathDocument 转换为字符串

python - 将字典分组为可能的最小键值对集

c# - 什么是 DateRange 类的好 hashCode

python - 字典中特定键的总和值

python - 通过 python 中的键过滤列表中字典项的值

c# - 文件已存在时无法创建文件

c# - 在客户端将json字符串转换为json?

c# - Moq - 如何设置惰性界面

dictionary - 在 Golang 中,如果我将 struct 作为键,我可以自定义键比较吗?

c# - 加载图标/进度条