2014-10-07 231 views
37

有没有一种方法可以在影响所有泛型类的方式下以C#中的以下异常获取给定键的值?我认为这是微软在例外描述中的一个大错失。给定的密钥不在字典中。哪把钥匙?

"The given key was not present in the dictionary." 

一个更好的办法是:

"The given key '" + key.ToString() + "' was not present in the dictionary." 

解决方案可能涉及混入或派生类可能。

+11

这个问题似乎是无关紧要的,因为它是关于实现异常消息的咆哮,而不是编程问题。 – Servy 2014-10-07 20:08:37

+1

当然,您可以使用调试器来查明确切的上下文,从而找到密钥。 – Mephy 2014-10-07 20:09:25

+6

问题在于,调试器并不总是可用的,例如在读取日志文件时。 – Andreas 2014-10-07 20:10:47

回答

10

在一般情况下,答案是否定的

但是,您可以设置调试器在其中异常被抛出第一点破门。那时,不存在的密钥将作为调用堆栈中的值访问。

在Visual Studio中,该选项位于:

调试→例外... →公共语言运行库异常→ System.Collections.Generic

在那里,你可以检查时抛出框。


对于需要在运行时信息更加具体的实例,提供您的代码使用IDictionary<TKey, TValue>和不直接依赖于Dictionary<TKey, TValue>,你可以实现自己的字典类,它提供这种行为。

+0

这通常是我如何运行我的调试器 – AaronLS 2014-10-07 20:11:06

+0

Hi @Sam,你在调用堆栈的哪个点找到这个值? – user919426 2015-08-07 05:26:53

+0

VS 2017(v15.5.7)具有它:调试 - > Windows - >异常设置 - >然后检查System.Collections.Generic.KeyNotFoundException – 2018-02-27 20:21:09

4

如果要管理的关键失误,你应该使用TryGetValue

https://msdn.microsoft.com/en-gb/library/bb347013(v=vs.110).aspx

string value = ""; 
if (openWith.TryGetValue("tif", out value)) 
{ 
    Console.WriteLine("For key = \"tif\", value = {0}.", value); 
} 
else 
{ 
    Console.WriteLine("Key = \"tif\" is not found."); 
} 
+0

这假定它的密钥的预期用法不在那里。可能并非如此,它可能是一个例外情况 – Servy 2014-10-07 20:11:52

+0

非常感谢你 – 2017-12-20 03:24:17

37

当您试图索引的东西,是不是有这种异常被抛出,例如:

Dictionary<String, String> test = new Dictionary<String,String>(); 
test.Add("Key1,"Value1"); 
string error = test["Key2"]; 

很多时候,像对象一样的东西将是关键,这无疑使得难以获得。但是,你总是可以编写以下(甚至把它包起来的扩展方法):

if (test.ContainsKey(myKey)) 
    return test[myKey]; 
else 
    throw new Exception(String.Format("Key {0} was not found", myKey)); 

或更有效(感谢@ScottChamberlain)

T retValue; 
if (test.TryGetValue(myKey, out retValue)) 
    return retValue; 
else 
    throw new Exception(String.Format("Key {0} was not found", myKey)); 

微软选择不这样做,可能是因为它在大多数物体上使用时没用。它很简单,可以自己做,所以只需要自己推出!

+11

做'ContainsKey',那么索引器将导致两个查找字典。做一个'TryGetValue'只能是一次查找,你可以用布尔输出来选择你的if/else块。 – 2014-10-07 20:30:29

+1

@ScottChamberlain非常真实。作为附加实现添加。 – BradleyDotNET 2014-10-07 20:33:23

+0

尝试返回布尔值的test.keys.contains(key)。 – Kurkula 2015-04-03 20:35:12

相关问题