测试字典KeyNotFoundException

我有一个场景,其中有一个字典在给定时间可能有也可能没有键值。 我目前正在测试是否以下列方式存在该值,但是想知道这是否是最好的方法,或者是否有更好的方法来处理它。

int myInt; try { myInt = {Value From Dictionary}; } catch { myInt = 0; } 

任何输入? 谢谢。

看看字典的TryGetValue方法

  int myInt; if (!_myDictionary.TryGetValue(key, out myInt)) { myInt = 0; } 

有几个人建议使用ContainsKey。 如果你真的想要这个值,这不是一个好主意,因为它意味着2个查找 – 例如

 if (_myDictionary.ContainsKey(key)) // look up 1 { myInt = _myDictionary[key]; // look up 2 } 

这是一个例子给你

  using System; using System.Collections.Generic; class Program { static void Main() { Dictionary test = new Dictionary(); test.Add("one", "value"); // // Use TryGetValue to avoid KeyNotFoundException. // string value; if (test.TryGetValue("two", out value)) { Console.WriteLine("Found"); } else { Console.WriteLine("Not found"); } } } 

首先,使用try catch在这里不是一个好主意,你不必要地减慢代码,你可以使用ContainsKeyTryGetValue轻松完成

我建议使用TryGetValue解决方案,如下所述 – https://msdn.microsoft.com/en-us/library/kw5aaea4 ( v= TryGetValue (查看示例)

但你可以优化更多。 线myInt = 0; 像@Mark建议的那样多余。 TyGetValue自动设置default值( int0 )。

如果未找到密钥,则value参数将获取TValue类型的相应默认值; 例如,0(零)表示整数类型,false表示布尔类型,null表示引用类型。 https://msdn.microsoft.com/en-us/library/bb347013%28v=vs.110%29.aspx

所以最终的代码可能是

 int myInt; if (_myDictionary.TryGetValue(key, out myInt)) { [...] //codes that uses the value }else{ [...] //codes that does not use the value } 

要么 –

 int myInt; _myDictionary.TryGetValue(key, out myInt)) [...] //other codes. 

下一段是从文档ot TryGetValue复制 –

此方法结合了ContainsKey方法和Item属性的function。 如果未找到密钥,则value参数将获取TValue类型的相应默认值; 例如,0(零)表示整数类型,false表示布尔类型,null表示引用类型。 如果您的代码经常尝试访问不在字典中的键,请使用TryGetValue方法。 使用此方法比捕获Item属性抛出的KeyNotFoundException更有效。 该方法接近O(1)操作。

BTWContainsKeyTryGetValue都有运行时间O(1) 。 所以,它没关系,你可以使用任何。

如果您正在讨论通用字典,那么避免exception的最佳方法是使用ContainsKey方法在使用之前测试字典是否有密钥。