1

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

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

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

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

4

2 回答 2

2

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

你还没有展示你目前是如何尝试这样做的,但你可以使用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);
    }
}
于 2013-06-29T17:13:08.847 回答
2

使用ContainsKeyTryGetValue来检查密钥的存在。

string val = string.Empty;
 foreach (var ky in keys)
 {

                if (items.TryGetValue(ky, out val))
                {
                    Console.WriteLine(val);
                }

     }

或者

foreach (var ky in keys)
 {

   if (items.ContainsKey(ky))
    {
      Console.WriteLine(items[ky]);
    }
  }

虽然 TryGetValue 比 ContainsKey 快,但当您想从字典中提取值时使用它。如果您想检查键是否存在,请使用 ContainsKey。

于 2013-06-29T17:16:23.543 回答