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

Interface IList ใน C#

Interface IList ใน C#

IList (Non-generic) แทนคอลเลกชันที่เข้าถึงด้วย Index ได้ มีขนาดคงที่หรือไดนามิกได้ อยู่ใน System.Collections Legacy - ใช้ IList<T> แทน

Properties

Propertyคำอธิบาย
Countจำนวน Element
IsFixedSizeขนาดคงที่หรือไม่
IsReadOnlyRead-only หรือไม่
IsSynchronizedThread-safe หรือไม่
Item[int]Indexer (Get/Set Element at Index)

Methods

Methodคำอธิบาย
Add(object)เพิ่ม Item คืน Index
Clear()ล้างทั้งหมด
Contains(object)มี Item นี้หรือไม่
GetEnumerator()Enumerator สำหรับ Foreach
IndexOf(object)Index แรกที่เจอ (-1 ถ้าไม่มี)
Insert(index, object)แทรกที่ Index
Remove(object)ลบ Item แรกที่เจอ
RemoveAt(index)ลบที่ Index

ตัวอย่าง: ArrayList Implement IList


using System;
using System.Collections;

class Program
{
    static void Main()
    {
        IList list = new ArrayList(); // ArrayList Implements IList
        list.Add("Apple");
        list.Add("Banana");
        list.Add("Cherry");
        
        Console.WriteLine($"Count: {list.Count}"); // 3
        Console.WriteLine($"IsFixedSize: {list.IsFixedSize}"); // False
        Console.WriteLine($"Item[1]: {list[1]}"); // Banana
        
        list.Insert(1, "Blueberry"); // Insert at Index 1
        Console.WriteLine($"After Insert: {string.Join(", ", list.Cast())}");
        
        list.Remove("Banana");
        Console.WriteLine($"After Remove: {string.Join(", ", list.Cast())}");
    }
}


ผลลัพธ์


Count: 3
IsFixedSize: False
Item[1]: Banana
After Insert: Apple, Blueberry, Banana, Cherry
After Remove: Apple, Blueberry, Cherry

IList vs IList<T> (Generic)

FeatureIList (Non-generic)IList<T> (Generic)
Type SafetyObject (Boxing/Unboxing)Compile-time T
Performance (Value Types)Slow (Boxing)Fast
Methodsobject-basedT-based
NamespaceSystem.CollectionsSystem.Collections.Generic
ImplementersArrayList, ArrayList<T>, Array, Collection<T>

Array Implements IList


int[] arr = { 1, 2, 3 };
IList list = arr; // Array Implements IList
list.Add(4); // Runtime Error: Fixed Size!
// Array.IsFixedSize = true