บทความนี้สาธิตวิธีตรวจสอบว่า Array เป็นแบบอ่านอย่างเดียว (read-only) หรือไม่ และคุณสมบัติอื่นๆ โดยใช้ IsReadOnly และ IsFixedSize ใน C#
ตัวอย่างที่ 1: อาเรย์ว่าง — ตรวจสอบคุณสมบัติพื้นฐาน
using System;
public class Demo
{
public static void Main()
{
string[] products = new string[] { };
Console.WriteLine("One or more planets begin with 'E'? = {0}",
Array.Exists(products, ele => ele.StartsWith("E")));
Console.WriteLine("Is the array having fixed size? = " + products.IsFixedSize);
Console.WriteLine("Is the array read only? = " + products.IsReadOnly);
}
}
ผลลัพธ์
One or more planets begin with 'E'? = False Is the array having fixed size? = True Is the array read only? = False
ตัวอย่างที่ 2: อาเรย์มีข้อมูล — ตรวจสอบหลายเงื่อนไข
using System;
public class Demo
{
public static void Main()
{
string[] products = { "Mobiles", "Laptop", "Watches", "Books" };
Console.WriteLine("Products list...");
foreach (string s in products)
{
Console.WriteLine(s);
}
Console.WriteLine("\nOne or more products begin with the letter 'C'? = {0}",
Array.Exists(products, ele => ele.StartsWith("C")));
Console.WriteLine("One or more planets begin with 'D'? = {0}",
Array.Exists(products, ele => ele.StartsWith("D")));
Console.WriteLine("One or more products begin with the letter 'T'? = {0}",
Array.Exists(products, ele => ele.StartsWith("T")));
Console.WriteLine("One or more planets begin with 'E'? = {0}",
Array.Exists(products, ele => ele.StartsWith("E")));
Console.WriteLine("Is the array read only? = " + products.IsReadOnly);
}
}
ผลลัพธ์
Products list... Mobiles Laptop Watches Books One or more products begin with the letter 'C'? = False One or more planets begin with 'D'? = False One or more products begin with the letter 'T'? = False One or more planets begin with 'E'? = False Is the array read only? = False
สรุป
- คุณสมบัติ
IsReadOnlyของอาเรย์จะคืนค่าfalseเสมอ — อาเรย์ใน C# ไม่เคยเป็น read-only (สามารถแก้ไขสมาชิกได้เสมอ) - คุณสมบัติ
IsFixedSizeของอาเรย์จะคืนค่าtrueเสมอ — อาเรย์มีขนาดคงที่ ตั้งแต่สร้าง (ไม่สามารถเพิ่ม/ลบขนาดได้) - เมธอด
Array.Exists<T>(T[] array, Predicate<T> match)ใช้ค้นหาว่ามีสมาชิกตรงเงื่อนไขหรือไม่ — คืนค่าbool - Lambda expression
ele => ele.StartsWith("C")เป็น predicate สำหรับทดสอบเงื่อนไข - หากต้องการคอลเลกชันที่ขยายตัวได้ (resizeable) และ/หรือ read-only ควรใช้
List<T>หรือReadOnlyCollection<T>
ตารางเปรียบเทียบคุณสมบัติอาเรย์ vs List
| คุณสมบัติ | Array (T[]) | List<T> |
|---|---|---|
| IsFixedSize | true | false (ขยายได้) |
| IsReadOnly | false | false (แต่มี AsReadOnly()) |
| เพิ่ม/ลบสมาชิก | ไม่ได้ (ต้องสร้างใหม่) | ได้ (Add, Remove, Insert) |
| เข้าถึงโดยดัชนี | O(1) | O(1) |