在 C# 中 List 和 IList 有什麼區別?
C# 中 List 和 IList 的主要區別在於,List 是一個類,它表示一個按索引可訪問的物件列表,而 IList 是一個介面,它表示一個按索引可訪問的物件集合。IList 介面從兩個介面實現,它們是 ICollection 和 IEnumerable。
List 和 IList 用於表示一組物件。它們可以儲存整數、字串等物件。有方法可插入、移除元素、搜尋和分類 List 或 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP