c# - 这个 Dictionary<TKey, TValue> 异常怎么可能?

标签 c# .net exception dictionary

给定以下堆栈跟踪:

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/

相关文章:

c# - 我如何在 Git 中处理 Visual Studio 解决方案和项目文件?

c# - Blazor 添加 HttpClientHandler 以将 Jwt 添加到请求的 HTTP header

.net - 为匿名方法生成 IL

.net - 为 Windows 服务构建安装项目时出现问题?

c# - 图片上传不损失质量

java - 在 Java 的构造函数中尝试和捕获 block 是一种好习惯吗

c++ - 如何捕获所有类型的堆栈错误?

java - javafx 中的 java.lang.reflect.InitationTargetException 中的异常

c# - 如何检查单个数组包含相同的值

c# - 异步图像加载到列表框中