Lambda 可以引用“外部變量”,這些變量位於在其中定義 Lambda 的封閉方法或類型的範圍內。 將會存儲通過這種方法捕獲的變量以供在 Lambda 表達式中使用,即使變量將以其他方式超出範圍或被作爲垃圾回收。 必須明確地分配外部變量,然後才能在 Lambda 表達式中使用該變量。 下面的示例演示這些規則:
delegate bool D(); delegate bool D2(int i); class Test { D del; D2 del2; public void TestMethod(int input) { int j = 0; // Initialize the delegates with lambda expressions. // Note access to 2 outer variables. // del will be invoked within this method. del = () => { j = 10; return j > input; }; // del2 will be invoked after TestMethod goes out of scope. del2 = (x) => {return x == j; }; // Demonstrate value of j: // Output: j = 0 // The delegate has not been invoked yet. Console.WriteLine("j = {0}", j); // Invoke the delegate. bool boolResult = del(); // Output: j = 10 b = True Console.WriteLine("j = {0}. b = {1}", j, boolResult); } static void Main() { Test test = new Test(); test.TestMethod(5); // Prove that del2 still has a copy of // local variable j from TestMethod. bool result = test.del2(10); // Output: True Console.WriteLine(result); Console.ReadKey(); } }
下列規則適用於 Lambda 表達式中的變量範圍:
-
捕獲的變量將不會被作爲垃圾回收,直至引用變量的委託超出範圍爲止。
-
在外部方法中看不到 Lambda 表達式內引入的變量。
-
Lambda 表達式無法從封閉方法中直接捕獲 ref 或 out 參數。
-
Lambda 表達式中的返回語句不會導致封閉方法返回。
-
Lambda 表達式不能包含其目標位於所包含匿名函數主體外部或內部的 goto 語句、break 語句或 continue 語句。