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

วิธีตรวจสอบว่า StringCollection เป็น Read-Only หรือไม่ใน C#

บทความนี้สาธิตวิธีการตรวจสอบว่า StringCollection เป็น read-only หรือไม่ โดยใช้ property IsReadOnly พร้อมกับการตรวจสอบค่าด้วย Contains

ตัวอย่างที่ 1: ตรวจสอบ IsReadOnly และ Contains

using System;
using System.Collections.Specialized;

public class Demo
{
    public static void Main()
    {
        StringCollection stringCol = new StringCollection();
        String[] arr = new String[] { "100", "200", "300", "400", "500" };

        Console.WriteLine("Array elements...");
        foreach (string res in arr)
        {
            Console.WriteLine(res);
        }

        stringCol.AddRange(arr);

        Console.WriteLine("Is the StringCollection read-only? = " + stringCol.IsReadOnly);
        Console.WriteLine("Does the specified string is in the StringCollection? = " + stringCol.Contains("800"));
    }
}

ผลลัพธ์

Array elements...
100
200
300
400
500
Is the StringCollection read-only? = False
Does the specified string is in the StringCollection? = False

ตัวอย่างที่ 2: ตัวอย่างกับชื่อบุคคล

using System;
using System.Collections.Specialized;

public class Demo
{
    public static void Main()
    {
        StringCollection stringCol = new StringCollection();
        String[] arr = new String[] { "John", "Tim", "Kevin", "Bradman", "Katie", "Tom", "Nathan" };

        Console.WriteLine("String array elements...");
        foreach (string res in arr)
        {
            Console.WriteLine(res);
        }

        stringCol.AddRange(arr);

        Console.WriteLine("Is the StringCollection read-only? = " + stringCol.IsReadOnly);
        Console.WriteLine("Does the specified string is in the StringCollection? = " + stringCol.Contains("Tim"));
    }
}

ผลลัพธ์

String array elements...
John
Tim
Kevin
Bradman
Katie
Tom
Nathan
Is the StringCollection read-only? = False
Does the specified string is in the StringCollection? = True

คำอธิบายเพิ่มเติม

  • StringCollection.IsReadOnly คืนค่า false เสมอ - StringCollection ไม่เป็น read-only โดยค่าเริ่มต้น
  • Property นี้มาจาก interface IList ที่ StringCollection implement
  • Contains(string value) ตรวจสอบว่ามีค่าที่ระบุอยู่หรือไม่ คืนค่า bool
  • การค้นหาเป็น case-sensitive (แยกตัวพิมพ์ใหญ่เล็ก)
  • เวลา complexity ของ Contains: O(n) - linear search
  • StringCollection ไม่มี constructor ที่ทำให้เป็น read-only ได้โดยตรง