我有一段代码表示字典和搜索键数组。
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/