ภาพรวม
คุณสมบัติ ArrayList.IsFixedSize บอกว่า ArrayList มีขนาดคงที่หรือไม่ ArrayList ธรรมดาเป็น false (ขยายได้) แต่ wrapper จาก ArrayList.FixedSize() จะเป็น true
ตัวอย่างที่ 1: Synchronized Wrapper (ไม่ใช่ Fixed Size)
using System;
using System.Collections;
public class Demo
{
public static void Main(String[] args)
{
ArrayList list1 = new ArrayList();
list1.Add("One");
list1.Add("Two");
list1.Add("Three");
list1.Add("Four");
list1.Add("Five");
Console.WriteLine("Elements in ArrayList...");
foreach (string res in list1)
{
Console.WriteLine(res);
}
ArrayList list = ArrayList.Synchronized(list1);
Console.WriteLine("Is ArrayList synchronized? = " + list.IsSynchronized);
Console.WriteLine("Is ArrayList have a fixed size? = " + list.IsFixedSize);
}
}
ผลลัพธ์
Elements in ArrayList...
One
Two
Three
Four
Five
Is ArrayList synchronized? = True
Is ArrayList have a fixed size? = False
ตัวอย่างที่ 2: FixedSize Wrapper
using System;
using System.Collections;
public class Demo
{
public static void Main(String[] args)
{
ArrayList list1 = new ArrayList();
list1.Add("ABC");
list1.Add("BCD");
list1.Add("CDE");
list1.Add("DEF");
list1.Add("EFG");
list1.Add("GHI");
list1.Add("HIJ");
list1.Add("IJK");
list1.Add("JKL");
list1.Add("KLM");
Console.WriteLine("Elements in ArrayList...");
foreach (string res in list1)
{
Console.WriteLine(res);
}
ArrayList list = ArrayList.Synchronized(list1);
Console.WriteLine("Is ArrayList synchronized? = " + list.IsSynchronized);
ArrayList list2 = ArrayList.FixedSize(list1);
Console.WriteLine("Is ArrayList have a fixed size? = " + list2.IsFixedSize);
}
}
ผลลัพธ์
Elements in ArrayList...
ABC
BCD
CDE
DEF
EFG
GHI
HIJ
IJK
JKL
KLM
Is ArrayList synchronized? = True
Is ArrayList have a fixed size? = True
คำอธิบายเพิ่มเติม
ArrayList.FixedSize(list)คืนค่า wrapper ที่ ห้ามเพิ่ม/ลบ**องค์ประกอบ (Add, Remove, Insert, Clear โยน NotSupportedException) แต่**แก้ไขค่าที่มีอยู่ได้** (indexer set)IsFixedSize = trueหมายถึงขนาดคงที่ (ไม่เพิ่ม/ลบได้) ไม่ใช่ read-only- ArrayList ธรรมดา: IsFixedSize = false, IsReadOnly = false, IsSynchronized = false
- ใช้ FixedSize wrapper เมื่อต้องการป้องกันการเปลี่ยนแปลงขนาด แต่ยังแก้ไขค่าได้
- สำหรับโค้ดใหม่ ใช้
List<T>+ encapsulation (private setter) หรือIReadOnlyList<T>แทน