+1辛勤工作,托马斯。我将ReadOnlyDictionary向前走了一步。
就像戴尔的解决方案,我想删除Add()
,Clear()
,Remove()
从智能感知等。但是我希望我的派生对象得以实现IDictionary<TKey, TValue>
。
此外,我想破坏以下代码:(同样,Dale的解决方案也这样做)
ReadOnlyDictionary<int, int> test = new ReadOnlyDictionary<int,int>(new Dictionary<int, int> { { 1, 1} });
test.Add(2, 1); //CS1061
Add()行导致:
error CS1061: 'System.Collections.Generic.ReadOnlyDictionary<int,int>' does not contain a definition for 'Add' and no extension method 'Add' accepting a first argument
调用方仍然可以将其强制转换为IDictionary<TKey, TValue>
,但是NotSupportedException
如果您尝试使用非只读成员(来自Thomas的解决方案),则会引发。
无论如何,这是我想要的任何人的解决方案:
namespace System.Collections.Generic
{
public class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
const string READ_ONLY_ERROR_MESSAGE = "This dictionary is read-only";
protected IDictionary<TKey, TValue> _Dictionary;
public ReadOnlyDictionary()
{
_Dictionary = new Dictionary<TKey, TValue>();
}
public ReadOnlyDictionary(IDictionary<TKey, TValue> dictionary)
{
_Dictionary = dictionary;
}
public bool ContainsKey(TKey key)
{
return _Dictionary.ContainsKey(key);
}
public ICollection<TKey> Keys
{
get { return _Dictionary.Keys; }
}
public bool TryGetValue(TKey key, out TValue value)
{
return _Dictionary.TryGetValue(key, out value);
}
public ICollection<TValue> Values
{
get { return _Dictionary.Values; }
}
public TValue this[TKey key]
{
get { return _Dictionary[key]; }
set { throw new NotSupportedException(READ_ONLY_ERROR_MESSAGE); }
}
public bool Contains(KeyValuePair<TKey, TValue> item)
{
return _Dictionary.Contains(item);
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
_Dictionary.CopyTo(array, arrayIndex);
}
public int Count
{
get { return _Dictionary.Count; }
}
public bool IsReadOnly
{
get { return true; }
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return _Dictionary.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return (_Dictionary as IEnumerable).GetEnumerator();
}
void IDictionary<TKey, TValue>.Add(TKey key, TValue value)
{
throw new NotSupportedException(READ_ONLY_ERROR_MESSAGE);
}
bool IDictionary<TKey, TValue>.Remove(TKey key)
{
throw new NotSupportedException(READ_ONLY_ERROR_MESSAGE);
}
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
{
throw new NotSupportedException(READ_ONLY_ERROR_MESSAGE);
}
void ICollection<KeyValuePair<TKey, TValue>>.Clear()
{
throw new NotSupportedException(READ_ONLY_ERROR_MESSAGE);
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
{
throw new NotSupportedException(READ_ONLY_ERROR_MESSAGE);
}
}
}