如何固定Hashtable的大小并判断它是否有固定大小?
我正在尝试使用以下代码修复哈希表的大小。
Hashtable hashtable = new Hashtable(2);
//Add elements in the Hashtable
hashtable.Add("A", "Vijendra");
hashtable.Add("B", "Singh");
hashtable.Add("C", "Shakya");
hashtable.Add("D", "Delhi");
hashtable.Add("E", "Singh");
hashtable.Add("F", "Shakya");
hashtable.Add("G", "Delhi");
hashtable.Add("H", "Singh");
hashtable.Add("I", "Shakya");
hashtable.Add("J", "Delhi");
我已修复此哈希表的大小为 2,但我可以在其中添加 2 个以上元素,为什么会发生这种情况,我做错了什么?
我试图找出这个 Hashtable 是否有固定大小,而不是 hashtable.IsFixedSize,它总是返回 false
请告诉我哪里错了,或者还有其他方法..
I am trying to fix the size of the Hashtable with following code.
Hashtable hashtable = new Hashtable(2);
//Add elements in the Hashtable
hashtable.Add("A", "Vijendra");
hashtable.Add("B", "Singh");
hashtable.Add("C", "Shakya");
hashtable.Add("D", "Delhi");
hashtable.Add("E", "Singh");
hashtable.Add("F", "Shakya");
hashtable.Add("G", "Delhi");
hashtable.Add("H", "Singh");
hashtable.Add("I", "Shakya");
hashtable.Add("J", "Delhi");
I have fix the size of this Hashtable is 2 but I can add more than 2 elements in this, why this happen, I am doing somthing wrong?
I have tried to find out is this Hashtable have fix size of not with hashtable.IsFixedSize, it always returns false
Please tell me where I am wrong, or there is another way..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
添加完所需的所有元素后,您需要实现
IDictionary
的只读版本,然后可以使用它来禁止更改现有条目(查看子类化Hashtable
,并覆盖所有方法/属性更改值以引发NotSupportedException
)。然后,您可以覆盖IsReadOnly
和IsFixedSize
以返回您需要的任何值。我还建议您使用通用的
Dictionary
而不是Hashtable
,因为您可以通过值类型获得更好的编译时安全性和更好的性能。但是,您必须创建自己的IDictionary
的只读实现,因为所有 Dictionary 方法都不是虚拟的。Once you've added all the elements you need, you need to implement a read-only version of
IDictionary
that you can then use to disallow altering existing entries (look at subclassingHashtable
, and overriding all the methods/properties which alter values to throwNotSupportedException
). You can then overrideIsReadOnly
andIsFixedSize
to return whatever values you need.I would also recommend you use the generic
Dictionary<TKey, TValue>
instead ofHashtable
, as you get better compile-time safety and better performance with value types. However, you would have to create your own read-only implementation ofIDictionary<TKey, TValue>
, as none of the Dictionary methods are virtual.采用 int 容量参数的 HashTable 构造函数重载仅将其用作您应该能够容纳多少个值的提示。这可以提高哈希表填充时的速度和内存消耗,但它可以增长以容纳比初始容量更多的值。这就是为什么您可以添加 2 个以上的值。
The HashTable constructor overload that takes an int capacity parameter uses it only as a hint from you as to how many values it should be able to hold. This can improve the speed and memory consumption of the HashTable as it is populated, but it can grow to hold more values than this initial capacity. That is why you can add more than 2 values.