• 在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中这个行为得到了纠正,下图是同样程序的运行结果:

  • 相关阅读:
    GNU build system / autoconf 和 automake 生成 Makefile 文件
    使用you-get下载网站内嵌的视频
    ffmpeg偷懒
    GB28181的PS流完全分析(封装 / 分包发送 / 接收组包 / 解析)
    JRE与JDK的区别
    图解SQL的inner join、left join、right join、full outer join、union、union all的区别
    linux常用查看日志命令
    Hadoop2.6.2的Eclipse插件的使用
    path与classpath区别(转)
    在Eclipse上运行Spark(Standalone,Yarn-Client)
  • 原文地址:https://www.cnblogs.com/dereklovecc/p/4190765.html
Copyright © 2020-2023  润新知