ASP.NET 2.0 配合 .NET Framework 2.0 引入了兩項革命性的 C# 語言特性:泛型 與 匿名方法,極大提升了程式碼的重用性、型別安全性與開發效率。
泛型可應用於類別、方法、結構、介面、委派等設計中,兼具重用性、型別安全與高效率,是非泛型程式碼無法比擬的優勢。以 System.Collections.Generic.Stack<T> 為例,其概念宣告如下:
public class Stack<T>
{
T[] items;
int count;
public void Push(T item) { }
public T Pop() { }
}
三種型別參數約束 讓泛型更具彈性:
class 與 struct 關鍵字限定C# 1.x 時代,使用委派實作事件機制時,常需額外建立類別或方法,不僅繁瑣且不符直覺思維。匿名方法允許將程式碼區塊直接「內嵌」至委派使用處,讓委派與方法主體集中在一起。
class InputForm : Form
{
ListBox listBox;
TextBox textBox;
Button addButton;
public InputForm()
{
listBox = new ListBox();
textBox = new TextBox();
addButton = new Button();
addButton.Click += new EventHandler(AddClick);
}
void AddClick(object sender, EventArgs e)
{
listBox.Items.Add(textBox.Text);
}
}
class InputForm : Form
{
ListBox listBox;
TextBox textBox;
Button addButton;
public InputForm()
{
listBox = new ListBox();
textBox = new TextBox();
addButton = new Button();
addButton.Click += delegate { listBox.Items.Add(textBox.Text); };
}
}
匿名方法不僅減少樣板程式碼,更讓事件處理邏輯緊貼註冊位置,大幅提升程式碼可讀性與維護性,是現代 C# 事件驅動程式設計的基石之一。