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

ตรวจสอบว่าอาเรย์เป็นแบบอ่านอย่างเดียวหรือไม่ใน C#

บทความนี้สาธิตวิธีตรวจสอบว่า 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>
IsFixedSizetruefalse (ขยายได้)
IsReadOnlyfalsefalse (แต่มี AsReadOnly())
เพิ่ม/ลบสมาชิกไม่ได้ (ต้องสร้างใหม่)ได้ (Add, Remove, Insert)
เข้าถึงโดยดัชนีO(1)O(1)