这是怎么字典< TKEY的,TValue>异常可能吗? [英] How is this Dictionary<TKey, TValue> exception possible?

查看:181
本文介绍了这是怎么字典< TKEY的,TValue>异常可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于以下堆栈跟踪:

消息:值不能为null.Parameter名称:关键
来源:mscorlib程序
TARGETSITE:虚空ThrowArgumentNullException(System.ExceptionArgument)
堆栈跟踪:
   在System.ThrowHelper.ThrowArgumentNullException(ExceptionArgument参数)
   在System.Collections.Generic.Dictionary'2.FindEntry(TKEY的键)
   在System.Collections.Generic.Dictionary'2.get_Item(TKEY的键)
   在MyCompany.MAF.Agent.ServiceContracts.ConvertUtils.Convert(Dictionary'2从)在D:\开发\ MAF \代理\ MyCompany.MAF.Agent \ ServiceContracts \ ConvertUtils.cs:行11

我的结论是,code某种程度上以下块检索从输入字典的键集合空。然而,输入字典词典&LT的实例;字符串,字符串> 字典1所述的实施;字符串,字符串>使得该条件是不可能的。在添加一个项目有一个空键,则抛出异常。

  7内部静态KeyValuePair<字符串,字符串> []转换(IDictionary的<字符串,字符串>从)
 8 {
 9名单,其中,KeyValuePair<字符串,字符串>> RET =新的名单,其中,KeyValuePair<字符串,字符串>>();
10的foreach(在from.Keys字符串键)
11 ret.Add(新KeyValuePair<字符串,字符串>(键,从[关键]));
12返回ret.ToArray();
13}  

解决方案

我有这个问题频繁发生,因为我做了允许多个线程访问相同的字典的错误。请确保此情况并非如此,因为词典不是线程安全的。

(顺便说一句,你的方法可以大大简化词典< K,V> 已经是一个的IEnumerable< KeyValuePair< K,V>&GT ;。您应该能够只是做的ToArray 上一个

Given the following stack trace:

MESSAGE: Value cannot be null.Parameter name: key
SOURCE: mscorlib
TARGETSITE: Void ThrowArgumentNullException(System.ExceptionArgument)
STACKTRACE:
   at System.ThrowHelper.ThrowArgumentNullException(ExceptionArgument argument)
   at System.Collections.Generic.Dictionary'2.FindEntry(TKey key)
   at System.Collections.Generic.Dictionary'2.get_Item(TKey key)
   at MyCompany.MAF.Agent.ServiceContracts.ConvertUtils.Convert(Dictionary'2 from) in D:\Development\MAF\Agent\MyCompany.MAF.Agent\ServiceContracts\ConvertUtils.cs:line 11

I conclude that somehow the following block of code has retrieved a null from the input Dictionary's Keys collection. However, the input dictionary is an instance of Dictionary<string, string>. The implementation of Dictionary<string, string> makes that condition impossible. Upon adding an item with a null key, an exception is thrown.

  7 internal static KeyValuePair<string, string>[] Convert(IDictionary<string, string> from)
 8 {
 9     List<KeyValuePair<string, string>> ret = new List<KeyValuePair<string, string>>();
10     foreach (string key in from.Keys)
11         ret.Add(new KeyValuePair<string, string>(key, from[key]));
12     return ret.ToArray();
13 }

解决方案

I've had this problem happen frequently because I made the mistake of allowing multiple threads to access the same dictionary. Make sure that this is not the case, because Dictionary is not thread-safe.

(Incidentally, your method can be greatly simplified. Dictionary<K,V> is already an IEnumerable<KeyValuePair<K,V>>. You should be able to just do ToArray on one.

这篇关于这是怎么字典&LT; TKEY的,TValue&GT;异常可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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