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