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

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


ความแตกต่างหลัก ระหว่าง List และ IList ใน C# คือ List เป็นคลาสที่แสดงรายการของอ็อบเจ็กต์ที่สามารถเข้าถึงได้โดยดัชนี ในขณะที่ IList เป็นอินเทอร์เฟซที่แสดงถึงคอลเล็กชันของอ็อบเจ็กต์ที่สามารถเข้าถึงได้โดยดัชนี อินเทอร์เฟซ IList ใช้งานจากอินเทอร์เฟซ 2 อินเทอร์เฟซ ได้แก่ ICollection และ IEnumerable

List และ IList ใช้เพื่อแสดงถึงชุดของวัตถุ พวกเขาสามารถเก็บวัตถุที่เป็นจำนวนเต็ม สตริง ฯลฯ มีวิธีการแทรก ลบองค์ประกอบ ค้นหาและจัดเรียงองค์ประกอบของรายการหรือ IList ความแตกต่างที่สำคัญระหว่าง List และ IList คือ List เป็นคลาสที่เป็นรูปธรรม และ IList เป็นอินเตอร์เฟส โดยรวมแล้ว List เป็นประเภทที่เป็นรูปธรรมที่ใช้อินเทอร์เฟซ IList

ตัวอย่างที่ 1

using System;
using System.Collections.Generic;
namespace DemoApplication{
   class Demo{
      static void Main(string[] args){
         IList<string> ilist = new IList<string>();
         //This will throw error as we cannot create instance for an IList as it is an interface.
         ilist.Add("Mark");
         ilist.Add("John");
         foreach (string list in ilist){
            Console.WriteLine(list);
         }
      }
   }
}

ตัวอย่างที่ 2

using System;
using System.Collections.Generic;
namespace DemoApplication{
   class Demo{
      static void Main(string[] args){
         IList<string> ilist = new List<string>();
         ilist.Add("Mark");
         ilist.Add("John");
         List<string> list = new List<string>();
         ilist.Add("Mark");
         ilist.Add("John");
         foreach (string lst in ilist){
            Console.WriteLine(lst);
         }
         foreach (string lst in list){
            Console.WriteLine(lst);
         }
         Console.ReadLine();
      }
   }
}

ผลลัพธ์

ผลลัพธ์ของโค้ดด้านบนคือ

Mark
John
Mark
John