posts - 930,  comments - 588,  views - 402万
< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

      最近在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

posted on   PetterLiu  阅读(2497)  评论(0编辑  收藏  举报
编辑推荐:
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
阅读排行:
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· 【.NET】调用本地 Deepseek 模型
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
点击右上角即可分享
微信分享提示