简体   繁体   English

使Hashtable不变

[英]Make Hashtable immutable

How do I make a derived class from Hashtable, objects of which can be added, but cannot be removed or replaced? 我如何从Hashtable派生一个派生类,该对象可以添加但不能删除或替换?

What do I have to override and particularly how do I override the [] operator? 我必须重写什么,特别是如何重写[]运算符?

Instead of deriving from the Dictionary (which you should use rather than a HashTable), you should probably encapsulate it in this case. 在这种情况下,您可能应该封装它,而不是从Dictionary(应该使用它而不是HashTable)派生。

The Dictionary has a lot of methods that allow changing the collection, it's easier to make it a private member, and then just implement the methods to add and access items. 词典中有很多方法可以更改集合,使其成为私有成员更容易,然后只需实现添加和访问项目的方法即可。

Something like: 就像是:

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

}

At a minimum, you should override Clear , Remove , the property Values and the indexer Item . 至少,您应该覆盖ClearRemove ,属性Values和索引器Item You can override the indexer Item using the syntax: 您可以使用以下语法覆盖索引器Item

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

You need to override Clear so that a user can't clear the hashtable. 您需要覆盖Clear以便用户无法清除哈希表。 You need to override Remove so that a user can't remove entires from the hashtable. 您需要覆盖Remove以便用户无法从哈希表中删除整个内容。 You need to override Values because a user could use the ICollection that is returned to modify the values in the hashtable. 您需要覆盖Values因为用户可以使用返回的ICollection来修改哈希表中的值。 You need to override Item for a similar reason. 由于类似的原因,您需要覆盖Item

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM