这个词典<TKey,TValue>例外怎么可能?

goo*_*gic 8 .net c# dictionary exception

给出以下堆栈跟踪:

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
Run Code Online (Sandbox Code Playgroud)

我得出结论,以下代码块以某种方式从输入Dictionary的Keys集合中检索了一个null.但是,输入字典是一个实例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();
}
Run Code Online (Sandbox Code Playgroud)

Jac*_*cob 13

我经常遇到这个问题,因为我错误地允许多个线程访问同一个字典.确保不是这种情况,因为Dictionary它不是线程安全的.

(顺便说一句,你的方法可以大大简化. Dictionary<K,V>已经是一个IEnumerable<KeyValuePair<K,V>>.你应该能够做到ToArray一个.

  • +1,如果不使用锁保护它,则线程可以破坏内部结构并在存储桶中创建空条目.当元素数量增长到足以需要更多存储桶时,字典在重新组织时最容易受到攻击. (2认同)