Why can I not add null as a value when using ConcurrentDictionary?

余生长醉 提交于 2019-12-12 00:00:44

问题


Consider the following code:

// 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);                
            }
        }

What I want to do is simply create the entry in the dictionary if it does not exist yet; it should have no value though until something explicitly sets it. I get this exception though:

An unhandled exception of type 'System.ArgumentNullException' occurred in mscorlib.dll

Additional information: Value cannot be null.

The documentation states that key cannot be null, which makes sense. why am I getting this exception for a value though? Am I not understanding this method?


回答1:


Code ends up calling the other GetOrAdd that takes Func as argument (and it explicitly required not to be null - "key or valueFactory is null.").

public TValue GetOrAdd(TKey key,Func<TKey, TValue> valueFactory)...

Fix: specify type explicitly:

 values.GetOrAdd("test", (Object)null);

Why: C# always tries to find more specific match and Func<TKey, TValue> is more specific than Object - so that override is picked.



来源:https://stackoverflow.com/questions/37951035/why-can-i-not-add-null-as-a-value-when-using-concurrentdictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!