Dictionary<TKey, TValue>.ContainsKey 方法
2013/3/11
确定 Dictionary<TKey, TValue> 是否包含指定的键。
程序集: mscorlib(位于 mscorlib.dll 中)
| 异常 | 条件 |
|---|---|
| ArgumentNullException | key 为 null。 |
下面的代码示例演示了如何在调用 Add 方法之前使用 ContainsKey 方法测试某个键是否存在。该示例还演示如何使用 TryGetValue 方法来检索值,当程序频繁尝试词典中不存在的键时,这是一种很有效的方法。最后,此示例提供使用 Item 属性(C# 中的索引器)测试键是否存在,演示了效率最低的方法。
此代码示例摘自一个为 Dictionary<TKey, TValue> 类提供的更大示例。
// ContainsKey can be used to test keys before inserting // them. if (!openWith.ContainsKey("ht")) { openWith.Add("ht", "hypertrm.exe"); outputBlock.Text += String.Format("Value added for key = \"ht\": {0}", openWith["ht"]) + "\n"; } ... // When a program often has to try keys that turn out not to // be in the dictionary, TryGetValue can be a more efficient // way to retrieve values. string value = ""; if (openWith.TryGetValue("tif", out value)) { outputBlock.Text += String.Format("For key = \"tif\", value = {0}.", value) + "\n"; } else { outputBlock.Text += "Key = \"tif\" is not found." + "\n"; } ... // The indexer throws an exception if the requested key is // not in the dictionary. try { outputBlock.Text += String.Format("For key = \"tif\", value = {0}.", openWith["tif"]) + "\n"; } catch (KeyNotFoundException) { outputBlock.Text += "Key = \"tif\" is not found." + "\n"; }