给定的键不在字典中。哪个键? [英] The given key was not present in the dictionary. Which key?

查看:410
本文介绍了给定的键不在字典中。哪个键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在影响所有泛型类的方法中得到C#中以下异常中给定键的值?我认为这是微软的例外描述中的一个大错误。

Is there a way to get the value of the given key in the following exception in C# in a way that affects all generic classes? I think this is a big miss in the exception description from Microsoft.

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

更好的方法是:

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

解决方案可能涉及到mixins或派生类。

Solutions might involve mixins or derived classes maybe.

推荐答案

当您尝试索引到不在的东西时,抛出此异常,例如:

This exception is thrown when you try to index to something that isn't there, for example:

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

通常情况下,像对象这样的东西将成为关键,这无疑很难得到,但是你可以随时写下面的内容(甚至可以用扩展方法包装): / p>

Often times, something like an object will be the key, which undoubtedly makes it harder to get. However, you can always write the following (or even wrap it up in an extension method):

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

或更高效(谢谢@ScottChamberlain)

Or more efficient (thanks to @ScottChamberlain)

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

Microsoft选择不这样做,可能是因为在大多数对象上使用时是无用的,它很简单,只需要滚动你自己!

Microsoft chose not to do this, probably because it would be useless when used on most objects. Its simple enough to do yourself, so just roll your own!

这篇关于给定的键不在字典中。哪个键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆