为什么在使用 ConcurrentDictionary 时不能添加 null 作为值?
Why can I not add null as a value when using ConcurrentDictionary?
考虑以下代码:
// holds the actual values
private volatile ConcurrentDictionary<string, Object> values;
public object this[string key] {
get {
// exception is thrown on this line
return values.GetOrAdd(key, null);
}
set {
values.AddOrUpdate(key, value, (k, v) => value);
}
}
我想做的只是在字典中创建一个条目,如果它还不存在的话;在明确设置它之前,它应该没有任何价值。不过我得到了这个例外:
An unhandled exception of type 'System.ArgumentNullException' occurred in mscorlib.dll
Additional information: Value cannot be null.
文档中说key不能为null,这是有道理的。为什么我会得到一个值的异常?我不明白这种方法吗?
代码最终调用另一个以 Func
作为参数的 GetOrAdd(并且它明确要求不能为 null - "key or valueFactory is null.")。
public TValue GetOrAdd(TKey key,Func<TKey, TValue> valueFactory)...
修复:明确指定类型:
values.GetOrAdd("test", (Object)null);
原因:C# 始终尝试查找更具体的匹配项,并且 Func<TKey, TValue>
比 Object
更具体 - 因此选择了覆盖。
考虑以下代码:
// holds the actual values
private volatile ConcurrentDictionary<string, Object> values;
public object this[string key] {
get {
// exception is thrown on this line
return values.GetOrAdd(key, null);
}
set {
values.AddOrUpdate(key, value, (k, v) => value);
}
}
我想做的只是在字典中创建一个条目,如果它还不存在的话;在明确设置它之前,它应该没有任何价值。不过我得到了这个例外:
An unhandled exception of type 'System.ArgumentNullException' occurred in mscorlib.dll
Additional information: Value cannot be null.
文档中说key不能为null,这是有道理的。为什么我会得到一个值的异常?我不明白这种方法吗?
代码最终调用另一个以 Func
作为参数的 GetOrAdd(并且它明确要求不能为 null - "key or valueFactory is null.")。
public TValue GetOrAdd(TKey key,Func<TKey, TValue> valueFactory)...
修复:明确指定类型:
values.GetOrAdd("test", (Object)null);
原因:C# 始终尝试查找更具体的匹配项,并且 Func<TKey, TValue>
比 Object
更具体 - 因此选择了覆盖。