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