LINQ 小心Access to modified closure 问题

来源:互联网 发布:义乌涉外数据服务中心 编辑:程序博客网 时间:2024/05/29 14:48
http://www.cnblogs.com/wintersun/archive/2010/06/15/1758628.html
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

0 0
原创粉丝点击