给定以下堆栈跟踪:
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<string, string>
的一个实例. Dictionary<string, string>
的实现使那个条件不可能。添加具有空键的项目时,将引发异常。
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();
}
最佳答案
我经常遇到这个问题,因为我犯了允许多个线程访问同一个字典的错误。确保不是这种情况,因为 Dictionary
不是线程安全的。
(顺便说一下,你的方法可以大大简化。Dictionary<K,V>
已经是一个 IEnumerable<KeyValuePair<K,V>>
。你应该可以只对一个做 ToArray
。
关于c# - 这个 Dictionary<TKey, TValue> 异常怎么可能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2283455/