C# 闭包

http://www.cnblogs.com/birdwudi/archive/2010/08/20/1804342.html#top 很好的文章

1,闭包其实就是使用的变量已经脱离其作用域,却由于和作用域存在上下文关系,从而可以在当前环境中继续使用的一种函数对象。

2,闭包允许你将一些行为封装,将它像一个对象一样传来递去,而且它依然能够访问到原来第一次声明时的上下文。
3,使用lambda表示可以保留上下文的局部变量。如下:

        List<Action> act = new List<Action>();
        for (int i = 0; i < 10; i++)
        {
            int tmpIndex = i;
            act.Add(()=> {
                print("tmpIndex  " + tmpIndex);
            });
        }
        foreach (var item in act)
        {
            item();//打印0,1,2,3,,,9
        }
        act.Clear();//清空
        int tmpIndex2 = 0;
        for (int i = 0; i < 10; i++)
        {
            act.Add(() => {
                print("tmpIndex2  " + tmpIndex2);
            });
        }
        foreach (var item in act)
        {
            item();//打印0,0,0,,,都为0
        }

猜你喜欢

转载自blog.csdn.net/tran119/article/details/81366026