给定的关键是不存在的字典中,哪些关键? [英] The given key was not present in the dictionary, what key?

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

问题描述

有没有办法让在C#中的以下异常的影响所有泛型类的方式给定键的值?认为这是微软的异常说明一个大小姐。

Is there a way to get the value of the given key in the following exception in c# in a way that affect all generic classes? 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."



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

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"];

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

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 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天全站免登陆