Is there an IDictionary implementation that, on missing key, returns the default value instead of throwing?

前端 未结 15 1829
暗喜
暗喜 2020-11-27 04:00

The indexer into Dictionary throws an exception if the key is missing. Is there an implementation of IDictionary that instead will return de

15条回答
  •  轮回少年
    2020-11-27 04:42

    public class DefaultIndexerDictionary : IDictionary
    {
        private IDictionary _dict = new Dictionary();
    
        public TValue this[TKey key]
        {
            get
            {
                TValue val;
                if (!TryGetValue(key, out val))
                    return default(TValue);
                return val;
            }
    
            set { _dict[key] = value; }
        }
    
        public ICollection Keys => _dict.Keys;
    
        public ICollection Values => _dict.Values;
    
        public int Count => _dict.Count;
    
        public bool IsReadOnly => _dict.IsReadOnly;
    
        public void Add(TKey key, TValue value)
        {
            _dict.Add(key, value);
        }
    
        public void Add(KeyValuePair item)
        {
            _dict.Add(item);
        }
    
        public void Clear()
        {
            _dict.Clear();
        }
    
        public bool Contains(KeyValuePair item)
        {
            return _dict.Contains(item);
        }
    
        public bool ContainsKey(TKey key)
        {
            return _dict.ContainsKey(key);
        }
    
        public void CopyTo(KeyValuePair[] array, int arrayIndex)
        {
            _dict.CopyTo(array, arrayIndex);
        }
    
        public IEnumerator> GetEnumerator()
        {
            return _dict.GetEnumerator();
        }
    
        public bool Remove(TKey key)
        {
            return _dict.Remove(key);
        }
    
        public bool Remove(KeyValuePair item)
        {
            return _dict.Remove(item);
        }
    
        public bool TryGetValue(TKey key, out TValue value)
        {
            return _dict.TryGetValue(key, out value);
        }
    
        IEnumerator IEnumerable.GetEnumerator()
        {
            return _dict.GetEnumerator();
        }
    }
    

提交回复
热议问题