Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ตรวจสอบว่า Hashtable มีขนาดคงที่หรือไม่ใน C#

บทความนี้สาธิตวิธีตรวจสอบว่า Hashtable มีขนาดคงที่ (fixed size) หรือไม่ โดยใช้คุณสมบัติ IsFixedSize ใน C#

ตัวอย่างที่ 1: Hashtable ที่สร้างด้วยความจุเริ่มต้น 10

using System;
using System.Collections;

public class Demo
{
    public static void Main()
    {
        Hashtable hash = new Hashtable(10);
        hash.Add("1", "A");
        hash.Add("2", "B");
        hash.Add("3", "C");
        hash.Add("4", "D");
        hash.Add("5", "E");
        hash.Add("6", "F");
        hash.Add("7", "G");
        hash.Add("8", "H");
        hash.Add("9", "I");
        hash.Add("10", "J");

        Console.WriteLine("Is the Hashtable having fixed size? = " + hash.IsFixedSize);
    }
}

ผลลัพธ์

Is the Hashtable having fixed size? = False

ตัวอย่างที่ 2: Hashtable ทั่วไปพร้อมแสดงข้อมูล

using System;
using System.Collections;

public class Demo
{
    public static void Main()
    {
        Hashtable hash = new Hashtable();
        hash.Add("One", "Katie");
        hash.Add("Two", "John");
        hash.Add("Three", "Barry");
        hash.Add("Four", "");
        hash.Add("Five", "Harry");
        hash.Add("Six", "F");
        hash.Add("Seven", "Tom");
        hash.Add("Eight", "Andy");
        hash.Add("Nine", "I");
        hash.Add("Ten", "Tim");

        Console.WriteLine("Hashtable Key and Value pairs...");
        foreach (DictionaryEntry entry in hash)
        {
            Console.WriteLine("{0} and {1}", entry.Key, entry.Value);
        }

        Console.WriteLine("Is the Hashtable having fixed size? = " + hash.IsFixedSize);
    }
}

ผลลัพธ์

Hashtable Key and Value pairs...
One and Katie
Ten and Tim
Five and Harry
Three and Barry
Seven and Tom
Two and John
Four and 
Eight and Andy
Nine and I
Six and F
Is the Hashtable having fixed size? = False

สรุป

  • คุณสมบัติ IsFixedSize คืนค่า true หาก Hashtable มีขนาดคงที่ มิฉะนั้นคืนค่า false
  • Hashtable ทั่วไป (standard Hashtable) จะมี IsFixedSize = false เสมอ — สามารถเพิ่ม/ลบข้อมูลได้อย่างอิสระ
  • พารามิเตอร์ในคอนสตรัคเตอร์ new Hashtable(10) คือ ความจุเริ่มต้น (initial capacity) ไม่ใช่ขนาดคงที่ — Hashtable จะขยายตัวอัตโนมัติเมื่อเต็ม
  • คุณสมบัติ IsReadOnly ก็คืนค่า false เช่นกันสำหรับ Hashtable ปกติ
  • หากต้องการคอลเลกชันขนาดคงที่ ควรใช้ array หรือ ReadOnlyCollection<T> แทน
  • แนะนำ: ใช้ Dictionary<TKey, TValue> แทนในโค้ดสมัยใหม่ — ไม่มีคุณสมบัติ IsFixedSize เพราะ Dictionary ขยายตัวได้เสมอ