public class Program
{
public delegate void MyDelegate();
public static void Main(string[] args)
{
MyDelegate d = null;
for (int i = 1; i <= 5; i++)
{
MyDelegate tempD = delegate { Console.WriteLine(i); };
d += tempD;
}
d();
}
}
預期輸出: 1 2 3 4 5
實際輸出: 6 6 6 6 6
i 為實例欄位i 遞增至 6(滿足終止條件)
public class Program
{
public delegate void MyDelegate();
public static void Main(string[] args)
{
MyDelegate d = null;
for (int i = 1; i <= 5; i++)
{
int k = i; // 每次迭代建立新區域變數
MyDelegate tempD = delegate { Console.WriteLine(k); };
d += tempD;
}
d();
}
}
正確輸出: 1 2 3 4 5
原理:編譯器為每次迭代建立獨立巢狀類別實例,各自捕獲對應的 k 值。
匿名方法是 C# 2.0 強大功能,實現閉包捕獲區域變數,但需理解編譯器內部機制(巢狀類別、實例共用)才能避開陷阱。正確使用可大幅提升程式碼表達力。