使哈希表不可变
如何从 Hashtable 生成派生类,可以添加其中的对象,但不能删除或替换?
我必须覆盖什么,特别是如何覆盖 [] 运算符?
How do I make a derived class from Hashtable, objects of which can be added, but cannot be removed or replaced?
What do I have to override and particularly how do I override the [] operator?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这种情况下,您可能应该封装它,而不是从字典(您应该使用它而不是哈希表)派生。
Dictionary 有很多允许更改集合的方法,将其设为私有成员更容易,然后只需实现添加和访问项目的方法即可。
像这样的东西:
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:
您至少应该覆盖
Clear
、Remove
、属性Values
和索引器Item
。您可以使用以下语法覆盖索引器Item
:您需要覆盖
Clear
以便用户无法清除哈希表。您需要重写Remove
,以便用户无法从哈希表中删除整个内容。您需要重写Values
,因为用户可以使用返回的ICollection
来修改哈希表中的值。出于类似的原因,您需要重写Item
。At a minimum, you should override
Clear
,Remove
, the propertyValues
and the indexerItem
. You can override the indexerItem
using the syntax:You need to override
Clear
so that a user can't clear the hashtable. You need to overrideRemove
so that a user can't remove entires from the hashtable. You need to overrideValues
because a user could use theICollection
that is returned to modify the values in the hashtable. You need to overrideItem
for a similar reason.