Make Hashtable immutable
How do I make a derived class from Hashtable, objects of which can be added, 开发者_C百科but cannot be removed or replaced?
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.
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
. You can override the indexer Item
using the syntax:
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. You need to override Remove
so that a user can't remove entires from the hashtable. You need to override Values
because a user could use the ICollection
that is returned to modify the values in the hashtable. You need to override Item
for a similar reason.
精彩评论