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

  • 相关阅读:
    嵌入级联分类器
    AdaBoost 和 Real Adaboost 总结
    二分图匹配--匈牙利算法
    更新说明
    使用Visual Studio 2015 Community 开发windows服务
    C#字符串的不变性
    Windows 7 IIS HTTP 错误 500.21 – Internal Server Error 解决方法
    asp.net的请求管道事件
    Http请求过程
    css简单学习属性2---背景图片
  • 原文地址:https://www.cnblogs.com/dereklovecc/p/4190765.html
Copyright © 2011-2022 走看看