public bool TryGetValue ( TKey key, out TValue value )参数
-
key
-
要获取的值的键。
-
value
-
当此方法返回值时,如果找到该键,便会返回与指定的键相关联的值;否则,则会返回 value 参数的类型默认值。该参数未经初始化即被传递。
返回值
如果 Dictionary 包含具有指定键的元素,则为 true;否则为 false。string value = ""; if (openWith.TryGetValue("tif", out value)) { Console.WriteLine("For key = /"tif/", value = {0}.", value); } else { Console.WriteLine("Key = /"tif/" is not found."); } ... // The indexer throws an exception if the requested key is // not in the dictionary. try { Console.WriteLine("For key = /"tif/", value = {0}.", openWith["tif"]); } catch (KeyNotFoundException) { Console.WriteLine("Key = /"tif/" is not found."); }
本文介绍了C#中Dictionary类的TryGetValue方法的使用方法。通过示例代码展示了如何安全地从字典中获取值,避免因键不存在而抛出异常。同时对比了TryGetValue方法与索引器的不同之处。
1735

被折叠的 条评论
为什么被折叠?



