C# 2.0 引入四大語言擴展,奠定現代 C# 開發基礎。本文快速瀏覽 泛型、匿名方法、迭代器、部分類型 的核心語法與優勢。
public class Stack
{
T[] _items; int _count;
public void Push(T item) { ... }
public T Pop() { ... }
}
var intStack = new Stack();
intStack.Push(3);
int x = intStack.Pop(); // 無裝箱/拆箱,編譯期型別安全
public class Dictionary where K : IComparable
{
public void Add(K key, V value) { ... }
}
var dict = new Dictionary();
dict.Add("Key", new Customer());
button.Click += delegate { listBox.Items.Add(textBox.Text); };
// 需參數時
button.Click += delegate(object s, EventArgs e)
{
MessageBox.Show(((Button)s).Text);
};
delegate int D();
static D F()
{
int x = 0;
return delegate { return ++x; }; // 捕獲 x,生命週期延長
}
public class Stack : IEnumerable
{
public IEnumerator GetEnumerator()
{
for (int i = _count - 1; i >= 0; --i)
yield return _items[i];
}
}
// 自動支援 foreach
foreach (int i in stack) Console.Write(i + " ");
public IEnumerable TopToBottom => this;
public IEnumerable BottomToTop
{
get { for (int i = 0; i < _count; i++) yield return _items[i]; }
}
// Generated.cs
public partial class Customer { private int Id; public Customer() { } }
// Custom.cs
public partial class Customer { public void SubmitOrder(Order o) { } }
編譯時合併為單一類別,適合程式碼產生器與手寫邏輯分離。
無新增關鍵字,where/yield/partial 僅在特定語境有特殊含義,既有代碼零衝突升級。
C# 2.0 四大特性解決了 1.x 時代的型別安全、委派冗長、集合遍歷困難、大型類別維護等痛點,是進階 C# 開發者必須精通的核心知識。