How to get around lack of covariance with IReadOnlyDictionary?

后端 未结 5 923
庸人自扰
庸人自扰 2020-12-01 17:48

I\'m trying to expose a read-only dictionary that holds objects with a read-only interface. Internally, the dictionary is write-able, and so are the objects within (see belo

5条回答
  •  情歌与酒
    2020-12-01 18:26

    You could write your own read-only wrapper for the dictionary, e.g.:

    public class ReadOnlyDictionaryWrapper : IReadOnlyDictionary where TValue : TReadOnlyValue
    {
        private IDictionary _dictionary;
    
        public ReadOnlyDictionaryWrapper(IDictionary dictionary)
        {
            if (dictionary == null) throw new ArgumentNullException("dictionary");
            _dictionary = dictionary;
        }
        public bool ContainsKey(TKey key) { return _dictionary.ContainsKey(key); }
    
        public IEnumerable Keys { get { return _dictionary.Keys; } }
    
        public bool TryGetValue(TKey key, out TReadOnlyValue value)
        {
            TValue v;
            var result = _dictionary.TryGetValue(key, out v);
            value = v;
            return result;
        }
    
        public IEnumerable Values { get { return _dictionary.Values.Cast(); } }
    
        public TReadOnlyValue this[TKey key] { get { return _dictionary[key]; } }
    
        public int Count { get { return _dictionary.Count; } }
    
        public IEnumerator> GetEnumerator()
        {
            return _dictionary
                        .Select(x => new KeyValuePair(x.Key, x.Value))
                        .GetEnumerator();
        }
    
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }
    }
    

提交回复
热议问题