Interface IList ใน C#
IList (Non-generic) แทนคอลเลกชันที่เข้าถึงด้วย Index ได้ มีขนาดคงที่หรือไดนามิกได้ อยู่ใน System.Collections Legacy - ใช้ IList<T> แทน
Properties
| Property | คำอธิบาย |
Count | จำนวน Element |
IsFixedSize | ขนาดคงที่หรือไม่ |
IsReadOnly | Read-only หรือไม่ |
IsSynchronized | Thread-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
ผลลัพธ์
Count: 3
IsFixedSize: False
Item[1]: Banana
After Insert: Apple, Blueberry, Banana, Cherry
After Remove: Apple, Blueberry, Cherry
IList vs IList<T> (Generic)
| Feature | IList (Non-generic) | IList<T> (Generic) |
| Type Safety | Object (Boxing/Unboxing) | Compile-time T |
| Performance (Value Types) | Slow (Boxing) | Fast |
| Methods | object-based | T-based |
| Namespace | System.Collections | System.Collections.Generic |
| Implementers | ArrayList, Array | List<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