这个词典如何?TKey,TValue>例外可能吗 [英] How is this Dictionary<TKey, TValue> exception possible?
问题描述
给定以下堆栈跟踪:
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
我得出以下结论:以下代码块从输入Dictionary的Keys集合中检索到一个null。但是,输入字典是 Dictionary< string,string>
的实例。 Dictionary < ;
使得条件不可能。在添加具有空键的项目时,会抛出异常。
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.
internal static KeyValuePair<string, string>[] Convert(IDictionary<string, string> from)
{
List<KeyValuePair<string, string>> ret = new List<KeyValuePair<string, string>>();
foreach (string key in from.Keys)
ret.Add(new KeyValuePair<string, string>(key, from[key]));
return ret.ToArray();
}
推荐答案
我遇到过这个问题经常发生,因为我犯了允许多个线程访问同一个字典的错误。确保不是这种情况,因为字典
不是线程安全的。
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.
(顺便说一句,你的方法可以大大简化字典< K,V>
已经是一个 IEnumerable< KeyValuePair< K,V>
您应该可以在 ToArray
之间。
(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.
这篇关于这个词典如何?TKey,TValue>例外可能吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!