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

ArrayList.IsFixedSize Property ใน C#

ArrayList.IsFixedSize Property ตรวจสอบว่า ArrayList มีขนาดคงที่หรือไม่ (คืนค่า bool)

  • true = ขนาดคงที่ ไม่สามารถ Add/Remove ได้
  • false = ขนาดเปลี่ยนแปลงได้ (ปกติ)

ตัวอย่าง

using System;
using System.Collections;

class Demo
{
    public static void Main()
    {
        ArrayList arrList = new ArrayList();
        
        Console.WriteLine("Adding some numbers:");
        arrList.Add(45);
        arrList.Add(78);
        
        Console.WriteLine("Count: " + arrList.Count); // 2
        Console.WriteLine("IsFixedSize: " + arrList.IsFixedSize); // False
    }
}

ผลลัพธ์

Adding some numbers:
2
IsFixedSize: False

ทำให้ ArrayList เป็น Fixed Size

ArrayList fixedList = ArrayList.FixedSize(arrList);
// fixedList.Add(100); // NotSupportedException!

ArrayList vs List<T>

คุณสมบัติArrayListList<T>
Type Safetyไม่มี (Object)มี (Generic)
PerformanceBoxing/Unboxingไม่มี Boxing
IsFixedSizeมี Property นี้ไม่มี (ใช้ AsReadOnly())
สถานะLegacy (Non-generic)แนะนำให้ใช้

List<T> ทำ Read-Only ได้อย่างไร

var list = new List<int> { 1, 2, 3 };
var readOnly = list.AsReadOnly(); // ReadOnlyCollection<int>
// readOnly.Add(4); // Compile Error