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

ความแตกต่างระหว่าง List และ IList ใน C#

ความแตกต่างหลัก

คุณสมบัติList<T>IList<T>
TypeConcrete Class (Class จริง)Interface
Instantiatenew List<T>() ได้new IList<T>() ไม่ได้
InheritanceImplements IList<T>, ICollection<T>, IEnumerable<T>Extends ICollection<T>, IEnumerable<T>
Featuresมี Method ครบ: Sort, Find, BinarySearch, ConvertAll, AsReadOnly...Method พื้นฐาน: Add, Remove, IndexOf, Insert, this[index]
UsageImplementation Detail (Internal)Abstraction (Parameter, Return Type, Property)

ตัวอย่างที่ 1: Error - ไม่สามารถ new IList ได้

// ❌ Compile Error: Cannot create instance of interface
IList<string> list = new IList<string>(); 
list.Add("Mark");

ตัวอย่างที่ 2: ใช้ IList เป็น Reference Type (Best Practice)

using System;
using System.Collections.Generic;

namespace DemoApplication
{
    class Demo
    {
        static void Main(string[] args)
        {
            // ใช้ IList เป็น Reference - Programming to Interface
            IList<string> iList = new List<string>();
            iList.Add("Mark");
            iList.Add("John");
            
            // หรือใช้ List โดยตรง
            List<string> list = new List<string>();
            list.Add("Mark");
            list.Add("John");
            
            // ทั้งคู่ทำงานได้เหมือนกัน
            PrintList(iList);
            PrintList(list);
            
            Console.ReadLine();
        }
        
        // รับ IList - ยืดหยุ่นกว่า รับ List
        static void PrintList(IList<string> items)
        {
            foreach (string item in items)
            {
                Console.WriteLine(item);
            }
        }
    }
}

Output

Mark
John
Mark
John

เมื่อไหร่ควรใช้ตัวไหน?

ใช้ List<T> เมื่อ:

  • Implementation ภายใน Class (Private Field, Local Variable)
  • ต้องการ Method เฉพาะ: Sort(), Find(), BinarySearch(), ConvertAll(), ForEach()
  • Performance Critical (Direct Access, No Interface Dispatch)

ใช้ IList<T> เมื่อ:

  • Method Parameter: void Process(IList<T> items)
  • Return Type: IList<T> GetItems()
  • Property: public IList<T> Items { get; }
  • Dependency Injection / Mocking (Unit Test)
  • อาจสลับ Implementation อื่นได้ (เช่น Array, Custom Collection)

ความสัมพันธ์ Hierarchy

IEnumerable<T>
    ↑
ICollection<T> (Count, Add, Remove, Clear, Contains, CopyTo)
    ↑
IList<T> (Indexer, IndexOf, Insert, RemoveAt)
    ↑
List<T> (Sort, Find, BinarySearch, Capacity, TrimExcess, AsReadOnly...)
    ↑
Array (Implements IList<T> แบบ Read-only size)