在Lambda表达式中使用循环变量

在C#5.0之前,如果在foreach循环中的lambda表达式里使用循环变量,那么你会发现一些意想不到的现象,例子如下:

            var integers = new List<int> { 1, 2, 3, 4 };
            var actions = new List<Action>();
            foreach (var integer in integers)
            {
                actions.Add(() => Console.WriteLine(integer));
            }
            actions.ForEach(action => action());

这段代码的输出并不是所期望的
1

2

3

4

而是

4

4

4

4

原因是actions里的lambda表达式所捕获的循环变量被覆盖了,而循环变量的最后一个值是4. 解决方法是引入一个局部变量来让lambda表达式捕获或者使用Foreach扩展函数:

            var action1s = new List<Action>();
            foreach (var integer in integers)
            {
                var tmpInt = integer;
                action1s.Add(() => Console.WriteLine(tmpInt));
            }
            action1s.ForEach(action => action());
            var action2s = new List<Action>();
            integers.ForEach(interger => action2s.Add(() => Console.WriteLine(interger)));
            action2s.ForEach(action => action());

完整的例子代码和输出结果如下:

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("foreach (var integer in integers)");
            var integers = new List<int> { 1, 2, 3, 4 };
            var actions = new List<Action>();
            foreach (var integer in integers)
            {
                actions.Add(() => Console.WriteLine(integer));
            }
            actions.ForEach(action => action());

            Console.WriteLine("foreach (var integer in integers) with local variable");
            var action1s = new List<Action>();
            foreach (var integer in integers)
            {
                var tmpInt = integer;
                action1s.Add(() => Console.WriteLine(tmpInt));
            }
            action1s.ForEach(action => action());

            Console.WriteLine("use ForEach extension method");
            var action2s = new List<Action>();
            integers.ForEach(interger => action2s.Add(() => Console.WriteLine(interger)));
            action2s.ForEach(action => action());
            Console.WriteLine("done");
            Console.Read();
        }
    }

在C#5.0中这个行为得到了纠正,下图是同样程序的运行结果:

 

转载于:https://www.cnblogs.com/dereklovecc/p/4190765.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值