<MSDN笔记> Lambda 表达式中的变量作用域

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace lamda1
{
    class Program
    {
        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; };

                j = 5;//del() is still true.
                Console.WriteLine("del2(5) = {0}", del2(5)); //j=10 also couldn't be seen by another delegate.

                // 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();
            }
        }
    }
}



The following rules apply to variable scope in lambda expressions:

  • A variable that is captured will not be garbage-collected until the delegate that references it goes out of scope.

  • Variables introduced within a lambda expression are not visible in the outer method.

  • A lambda expression cannot directly capture a ref or out parameter from an enclosing method.

  • A return statement in a lambda expression does not cause the enclosing method to return.

  • A lambda expression cannot contain a goto statement, break statement, or continue statement whose target is outside the body or in the body of a contained anonymous function.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值