C# 2.0 引入四大語言擴展,極大增強了型別安全性、表達能力與開發效率。本文系統整理 泛型、匿名方法、迭代器、部分型別 的核心概念、語法與實戰優勢。
非泛型集合使用 object 儲存資料,導致三大問題:
InvalidCastExceptionpublic class Stack
{
T[] items;
int count;
public void Push(T item) { ... }
public T Pop() { ... }
}
// 使用時指定型別參數
Stack intStack = new Stack();
intStack.Push(3);
int x = intStack.Pop(); // 無需轉型,編譯期型別安全
Stack custStack = new Stack();
custStack.Push(new Customer());
// custStack.Push(3); // 編譯錯誤:型別不符
public class Dictionary where K : IComparable
{
public void Add(K key, V value) { ... }
public V this[K key] { ... }
}
// 使用
var dict = new Dictionary();
dict.Add("Peter", new Customer());
where K : IComparable 確保鍵型別可比較,編譯期即檢查,避免執行期轉型失敗。
void PushMultiple(Stack stack, params T[] values)
{
foreach (var v in values) stack.Push(v);
}
// 呼叫時可省略 ,編譯器自動推斷
PushMultiple(intStack, 1, 2, 3, 4);
// 傳統寫法
button.Click += new EventHandler(Button_Click);
// 匿名方法
button.Click += delegate { listBox.Items.Add(textBox.Text); };
// 需存取參數時
button.Click += delegate(object sender, EventArgs e)
{
MessageBox.Show(((Button)sender).Text);
};
匿名方法可直接內嵌於委派註冊處,並自動捕獲外部區域變數(閉包)。
delegate int D();
static D F()
{
int x = 0;
return delegate { return ++x; }; // 捕獲 x
}
static void Main()
{
D d = F();
Console.WriteLine(d()); // 1
Console.WriteLine(d()); // 2
Console.WriteLine(d()); // 3
}
被捕獲的區域變數生命週期延長至委派可被 GC 回收為止。
實作 IEnumerable<T> 或 IEnumerator<T> 變得極簡單:
public class Stack : IEnumerable
{
T[] items; int count;
public IEnumerator GetEnumerator()
{
for (int i = count - 1; i >= 0; --i)
yield return items[i];
}
}
// 使用 foreach 自動呼叫 GetEnumerator
foreach (int i in stack) Console.Write(i + " ");
透過屬性回傳不同迭代器:
public IEnumerable TopToBottom { get { return this; } }
public IEnumerable BottomToTop
{
get
{
for (int i = 0; i < count; i++) yield return items[i];
}
}
// File1.cs (機器產生)
public partial class Customer
{
private int id;
private string name;
public Customer() { ... }
}
// File2.cs (手寫擴充)
public partial class Customer
{
public void SubmitOrder(Order o) { ... }
public bool HasOutstandingOrders() { ... }
}
編譯時自動合併,適用於:
C# 2.0 未新增任何關鍵字,where、yield、partial 僅在特定語境有特殊含義,仍可作為識別碼使用,確保既有代碼零衝突升級。
C# 2.0 的四大特性奠定了現代 C# 開發基石:泛型提供型別安全與效能,匿名方法簡化事件處理,迭代器讓集合遍歷直觀,部分型別支援大型專案協作。掌握它們,是進階 C# 開發者的必修課。