1

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

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

4

2 回答 2

5

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

Dictionary 有很多允许更改集合的方法,将其设置为私有成员更容易,然后只需实现添加和访问项目的方法。

就像是:

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

}
于 2009-10-19T16:33:45.587 回答
3

至少,您应该覆盖Clear, Remove, 属性Values和 indexer ItemItem您可以使用以下语法覆盖索引器:

public override this[object key] {
    get { // get implementation }
    set { // set implementation }
}

您需要覆盖Clear,以便用户无法清除哈希表。您需要覆盖Remove,以便用户无法从哈希表中删除整体。您需要覆盖Values,因为用户可以使用ICollection返回来修改哈希表中的值。Item出于类似的原因,您需要覆盖。

于 2009-10-19T16:27:59.987 回答