LINQ 小心Access to modified closure 问题

      最近在VisualStudio中Edit Source Code, Resharp plugin 在一处CODE上提示:Access to modified closure 。后面得知这是和闭包有关系,先看下面的CODE:

   1:              // First build a list of actions
   2:              List<Action> actions = new List<Action>();
   3:              for (int counter = 0; counter < 10; counter++)
   4:              {
   5:                  actions.Add(() => Console.WriteLine(counter));
   6:              }
   7:              // Then execute them
   8:              foreach (Action action in actions)
   9:              {
  10:                  action();
  11:              }

       一眼看上去,你以为会output 0-9,但实际上output 十个10. 这是什么原因呢?我们知道匿名函数有Capture变量的特性,上面我们声名了一个counter变量,然后相同counter变量被所有的Action实例捕捉到,所以将输出十行10的字符。如何解决这个问题,只要引入一个额外的变量在这个循环中就可以,如下的CODE:

   1:              // First build a list of actions
   2:              List<Action> actions = new List<Action>();
   3:              for (int counter = 0; counter < 10; counter++)
   4:              {
   5:                  int counter1 = counter;
   6:                  actions.Add(() => Console.WriteLine(counter1));
   7:              }
   8:              // Then execute them
   9:              foreach (Action action in actions)
  10:              {
  11:                  action();
  12:              }

       再看几个例子,都是有问题的:

   1:              // First build a list of actions
   2:  foreach (Attribute a in requiredAttributes) 
   3:  { 
   4:      result = result.Where(p => p.Attributes.Contains(a)); 
   5:  } 

   1:  List<string> keys = FillKeys() 
   2:  foreach (string key in keys){ 
   3:      q = q.Where(c => c.Company.Name.Contains(key)); 
   4:  } 

      完了,希望这篇POST对您开发有帮助!

      还可以参考:

       Comparing capture strategies: complexity vs power


作者:Petter Liu
出处:http://www.cnblogs.com/wintersun/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
该文章也同时发布在我的独立博客中-Petter Liu Blog

你可能感兴趣的:(closure)