这是怎么字典&LT; TKEY的,TValue&GT;异常可能吗? [英] How is this Dictionary<TKey, TValue> exception possible?
问题描述
由于以下堆栈跟踪:
消息:值不能为null.Parameter名称:关键
来源:mscorlib程序
TARGETSITE:虚空ThrowArgumentNullException(System.ExceptionArgument)
堆栈跟踪:
&NBSP;&NBSP;&NBSP;在System.ThrowHelper.ThrowArgumentNullException(ExceptionArgument参数)
&NBSP;&NBSP;&NBSP;在System.Collections.Generic.Dictionary'2.FindEntry(TKEY的键)
&NBSP;&NBSP;&NBSP;在System.Collections.Generic.Dictionary'2.get_Item(TKEY的键)
&NBSP;&NBSP;&NBSP;在MyCompany.MAF.Agent.ServiceContracts.ConvertUtils.Convert(Dictionary'2从)在D:\开发\ MAF \代理\ MyCompany.MAF.Agent \ ServiceContracts \ ConvertUtils.cs:行11
我的结论是,code某种程度上以下块检索从输入字典的键集合空。然而,输入字典词典&LT的实例;字符串,字符串&GT; 字典1所述的实施;字符串,字符串&GT;使得该条件是不可能的。在添加一个项目有一个空键,则抛出异常。
7内部静态KeyValuePair&LT;字符串,字符串&GT; []转换(IDictionary的&LT;字符串,字符串&GT;从)
8 {
9名单,其中,KeyValuePair&LT;字符串,字符串&GT;&GT; RET =新的名单,其中,KeyValuePair&LT;字符串,字符串&GT;&GT;();
10的foreach(在from.Keys字符串键)
11 ret.Add(新KeyValuePair&LT;字符串,字符串&GT;(键,从[关键]));
12返回ret.ToArray();
13}
我有这个问题频繁发生,因为我做了允许多个线程访问相同的字典的错误。请确保此情况并非如此,因为词典
不是线程安全的。
(顺便说一句,你的方法可以大大简化词典&LT; K,V&GT;
已经是一个的IEnumerable&LT; KeyValuePair&LT; K,V&GT;&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屋!