使Hashtable不可变

Ego*_*hin 1 c# overriding hashtable immutability

如何从Hashtable创建派生类,可以添加对象,但不能删除或替换?

我必须覆盖什么,特别是如何覆盖[]运算符?

Guf*_*ffa 5

您应该在这种情况下封装它,而不是派生自Dictionary(您应该使用而不是HashTable).

字典有很多方法可以更改集合,更容易使它成为私有成员,然后只需实现添加和访问项的方法.

就像是:

public class StickyDictionary<Key, Value> : IEnumerable<KeyValuePair<Key, Value>>{

   private Dictionary<Key, Value> _colleciton;

   public StickyDictionary() {
      _collection = new Dictionary<Key, Value>();
   }

   public void Add(Key key, Value value) {
      _collection.Add(key, value);
   }

   public Value this[Key key] {
      get {
         return _collection[key];
      }
   }

   public IEnumerable<KeyValuePair<Key, Value>> GetEnumerator() {
      return _collection.GetEnumerator();
   }

}
Run Code Online (Sandbox Code Playgroud)