C# 2.0(Visual Studio 2005)引入四大功能:泛型、迭代器、匿名方法、部分類型,極大提升開發效能。本文深入探討前三項。
泛型非 C# 獨有,CLR 與 MSIL 皆擴展支援,C#、VB.NET、Managed C++、J# 共享。泛型讓同一份代碼為不同類型生成專屬版本,解決 1.x 時代 ArrayList 存 object 的三大痛點:
// 1.x 風格
public class List {
internal class Node { internal object val; internal Node next; }
public void AddHead(object t) { ... }
public object Head() { return first.val; }
}
// 2.0 泛型
public class List<ItemType> {
private class Node<ItemType> { internal ItemType val; internal Node<ItemType> next; }
public void AddHead(ItemType t) { ... }
public ItemType Head() { return first.val; }
}
// 使用
List<int> intList = new List<int>(); // 編譯器強制類型安全,零裝箱
!0)的 MSIL;object 版本(避免代碼膨脹);透過 where 限制型別參數必須實作特定介面或繼承特定基類,編譯器據此假設成員可用,省去強制轉型:
public class BinaryTree<ValType> where ValType : IComparable<ValType>, ISerializable { }
1.x 需手寫 IEnumerable/IEnumerator、狀態管理,動輒數十行。2.0 yield return 讓編譯器自動生成狀態機:
public class List {
public IEnumerable<object> Iterate() {
for (int i = 0; i < theList.Length; i++)
yield return theList[i];
}
}
六行代替三十行,Bug 少、維護易、開發快。編譯器生成的 MSIL 與手寫版本等效。
partial class 讓類別實作分散多檔案,主要服務 IDE/代碼產生器(如 Windows Forms 設計師、DataSet、Web 服務 Proxy),避免設計師代碼與手寫代碼混雜。限制:所有部分必須編譯進同一組件,無自動機制確保完整性,建議僅用於工具生成代碼。
// File1.cs
public partial class Form1 { private void InitializeComponent() { ... } }
// File2.cs
public partial class Form1 { public void MyMethod() { ... } }
新代碼優先採用泛型、介面約束、迭代器;既有代碼漸進式升級,降低遷移成本。