【问题标题】:How to fix the size of the Hashtable and find the whether it has fix size or not?如何固定 Hashtable 的大小并确定它是否具有固定大小?
【发布时间】:2011-02-28 15:00:43
【问题描述】:

我正在尝试使用以下代码修复 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");

我已将这个 Hashtable 的大小固定为 2,但我可以在其中添加超过 2 个元素,为什么会发生这种情况,我做错了什么?

我试图找出这个 Hashtable 的固定大小不是 hashtable.IsFixedSize,它总是返回 false

请告诉我我错在哪里,或者还有其他方法..

【问题讨论】:

    标签: c# asp.net hashtable collections


    【解决方案1】:

    添加完所有需要的元素后,您需要实现IDictionary 的只读版本,然后您可以使用它来禁止更改现有条目(查看子类化Hashtable,并覆盖所有方法/properties 改变值以抛出NotSupportedException)。然后,您可以覆盖 IsReadOnly 和 IsFixedSize 以返回您需要的任何值。

    我还建议您使用通用的Dictionary<TKey, TValue> 而不是Hashtable,因为您可以获得更好的编译时安全性和值类型的更好性能。但是,您必须创建自己的 IDictionary<TKey, TValue> 的只读实现,因为 Dictionary 方法都不是虚拟的。

    【讨论】:

      【解决方案2】:

      采用 int 容量参数的 HashTable 构造函数重载仅将其用作您关于它应该能够容纳多少值的提示。这可以提高 HashTable 在填充时的速度和内存消耗,但它可以增长到容纳比初始容量更多的值。这就是为什么您可以添加 2 个以上的值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-01-09
        • 2010-12-23
        • 1970-01-01
        • 1970-01-01
        • 2012-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多