zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    PHP调用WCF提供的方法
    关于git报 warning: LF will be replaced by CRLF in README.md.的警告的解决办法
    vue中引入mui报Uncaught TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them的错误
    微信小程序报Cannot read property 'setData' of undefined的错误
    Vue那些事儿之用visual stuido code编写vue报的错误Elements in iteration expect to have 'v-bind:key' directives.
    关于xampp中无法启动mysql,Attempting to start MySQL service...的解决办法!!
    PHP的环境搭建
    新手PHP连接MySQL数据库出问题(Warning: mysqli_connect(): (HY000/1045): Access denied for user 'root'@'localhost' (using password: YES))
    手机号码、获得当前时间,下拉框,填写限制
    团队作业(五):冲刺总结
  • 原文地址:https://www.cnblogs.com/wintersun/p/1758628.html
Copyright © 2011-2022 走看看