CodeGym /課程 /C# SELF /C# 集合中介面(interface)的角色

C# 集合中介面(interface)的角色

C# SELF
等級 28, 課堂 0
開放

1. 為什麼集合需要 interface?

老實說啦:當我們用具體型別寫程式時(像是 List<int>、Dictionary<string, string>),一切都很直觀。但想像一下,如果你突然想把 List<T> 換成 HashSet<T>,因為你只需要唯一值。或者你想寫一個方法,同時能處理這兩種集合。該怎麼辦?

要有一個統一的入口點——需要一個「通用插槽」。在 C# 裡,這個插槽就是 interface。它們定義了一組規則(方法、屬性),集合只要實作這個 interface,就能支援這些操作。

這就像手機充電器:只要有標準的 USB-C 插頭,你可以幫手機充電,也能幫現代吸塵器、甚至電動牙刷充電(重點是不要在黑暗中搞錯)。

實戰範例

假設你想寫一個方法,計算任何數字集合的總和。如果不用 interface,會長這樣:


// 這個方法只能處理陣列:
static int SumArray(int[] array)
{
    int sum = 0;
    for (int i = 0; i < array.Length; i++)
    {
        sum += array[i];
    }
    return sum;
} 

// 這個只能處理 List<int>:
static int SumList(List<int> list)
{
    int sum = 0;
    for (int i = 0; i < list.Count; i++)
        sum += list[i];
    return sum;
}

超不方便!明明程式碼幾乎一樣。用 IEnumerable<int> interface 就能寫成通用的:


static int SumAll(IEnumerable<int> collection)
{
    int sum = 0;
    foreach (var number in collection)
        sum += number;
    return sum;
}

現在這個方法可以吃任何實作 IEnumerable<int> 的集合:陣列、清單、集合等等。

2. 集合的主要 interface

在 .NET 裡,集合有幾個關鍵的 interface。簡單看一下——之後的課會細講每個怎麼實作。

介面 用途 實作這個介面的集合範例
IEnumerable<T>
列舉元素(foreach) 全部:
List<T>
、
HashSet<T>
、陣列
ICollection<T>
可變集合(Add、Remove、Count)
List<T>
、
HashSet<T>
、
Dictionary<K,V>
IList<T>
索引存取、修改
List<T>
、陣列
IDictionary<K,V>
處理「鍵-值」對
Dictionary<K,V>
、
SortedDictionary<K,V>
ISet<T>
集合(唯一元素)
HashSet<T>
、
SortedSet<T>

P.S. 為了簡單起見,這裡先不講這些 interface 之間的「多層繼承」。誰繼承誰——之後再說。

視覺化:集合 interface 樹狀圖


           IEnumerable<T>
                 ^
                 |
          ICollection<T>
              ^       ^
              |       |
         IList<T>  ISet<T>
              |       |
         List<T>   HashSet<T>
清單和集合的 interface 階層

對於字典:


           IEnumerable<KeyValuePair<K,V>>
                      ^
                      |
               ICollection<KeyValuePair<K,V>>
                      ^
                      |
               IDictionary<K,V>
                      |
                Dictionary<K,V>
字典的 interface 階層

3. interface 在現實開發中的意義?

靈活性

當你的方法或類別不是操作具體型別(像 List<int>),而是 interface(像 IEnumerable<int>),你就能傳進任何實作這個 interface 的集合。結果就是程式更靈活、可擴充。(不再只支援「只有 iPhone」——現在任何有 Bluetooth 的手機都行。)


static void PrintAll(IEnumerable<string> collection)
{
    foreach (var item in collection)
        Console.WriteLine(item);
}

現在你可以印出任何清單、陣列、集合,甚至 LINQ 查詢的結果!

統一化

如果你自己實作一個集合型別(比如某個很特殊的集合),只要實作對應的 interface——你的集合就能跟別人的程式碼合作,即使他們根本不知道你的集合存在。這也是為什麼 .NET 常說:「用 interface 編程,不要綁死在實作上」。

跟標準工具相容

支援標準 interface,你的集合就能跟 LINQ、排序、序列化等 .NET 功能一起玩。

4. List<T> —— 既是清單、也是集合、也是列舉

關於列舉的幾句話

IEnumerable<T> 是 .NET 集合最重要、最基礎的 interface。它只定義一個方法——GetEnumerator(),回傳一個 enumerator 物件讓你能遍歷集合。也因為這樣你才能寫:


foreach (var name in names)
{
    Console.WriteLine(name);
}

這裡 names 可以是清單、集合、甚至陣列。foreach 其實是語法糖,底層就是用 GetEnumerator()。

IEnumerable(沒有 <T>)是比較舊、沒泛型的版本。現在幾乎都用泛型版。

List 類別的宣告語法

來看看 List<T> 類別的宣告,稍微揭開它的神秘面紗:


public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, ...

這代表 List<T> 物件可以當作:

  • 可隨機索引的清單(IList<T>)
  • 可加/刪元素的集合(ICollection<T>)
  • 可以遍歷的元素集合(IEnumerable<T>)

範例:


List<string> names = new List<string> { "安娜", "鮑里斯", "瓦夏" };

// 當 IEnumerable - 可以用 foreach 走
IEnumerable<string> asEnumerable = names;
foreach (var n in asEnumerable) Console.WriteLine(n);

// 當 ICollection - 可以拿 Count:
ICollection<string> asCollection = names;
int count = asCollection.Count;

// 當 IList - 可以用索引存取:
IList<string> asList = names;
string firstItem = asList[0];

5. 應用範例

假設我們有一個簡單的用戶和角色管理小程式(我們在前幾堂課開始做的):


// 用戶類別
public class User
{
    public string Name { get; set; }
    public int Age { get; set; }
}

我們可以把用戶存在任何實作 IEnumerable<User> 的集合裡:


List<User> listUsers = new List<User> { new User { Name = "安娜", Age = 20 } };
HashSet<User> setUsers = new HashSet<User> { new User { Name = "鮑里斯", Age = 25 } };

// 印出所有用戶名字的方法
static void PrintUserNames(IEnumerable<User> users)
{
    foreach (var user in users)
        Console.WriteLine(user.Name);
}

// 用不同集合型別呼叫:
PrintUserNames(listUsers);
PrintUserNames(setUsers);

現在這個小程式變得超靈活——不用魔法、不用自訂 overload!

6. 常見錯誤與陷阱

最常見的錯誤之一——用太具體的型別,其實只需要 interface 就夠了:


// 不好(綁死在實作)
void DoSomethingWithList(List<int> numbers) { ... }

// 比較好(方法能處理任何集合)
void DoSomethingWithNumbers(IEnumerable<int> numbers) { ... }

另一個陷阱——忘了 interface 只定義它明講的操作。例如 IEnumerable<T> 沒有元素數量(Count),你得用 ICollection<T>,或自己算。

2
任務
C# SELF, 等級 28, 課堂 0
上鎖
為自訂集合實作 IEnumerable 介面
為自訂集合實作 IEnumerable 介面
留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION