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
- LINQ 小心Access to modified closure 问题
- Linq to DataSet 之Access查询
- Linq to DataSet 之Access查询
- linq to sql中慎用Where(Func predicate),小心被Linq给"骗"了!
- Linq to Sharepoint——使用Created,CreatedBy,Modified,ModifiedBy字段
- LINQ to SQL 效率问题
- Linq To Object查询问题
- linq to sql随机数问题
- Dblinq Linq To Mysql 问题
- Linq to sql 数据库连接问题
- Linq to Entity 的问题
- linq to Entity 左连接问题
- Linq to entity 3.5 左联接问题
- LINQ to SQL的默认值问题
- 关于Linq to sql更新的问题
- linq,linq to sql
- android开发中出现R.java was modified manually! Reverting to generated version!问题的解决方法
- JavaMail问题:Access to default session denied
- android检测网络是否连接,WIFI是否连接
- Mysql+C3P0+Hibernate,偶发性异常
- 数据结构8:队列的顺序存储结构表示和实现
- ext-basex.js处理的同步请求在Firefox12、谷歌最新版本中不支持(在Firefox11中是支持的)怎么办?(已解答)
- 第四周的作业
- LINQ 小心Access to modified closure 问题
- 如何为Apache配置第三方证书
- junit 4 测试运行器
- Algorithm Gossip: 费式数列
- 金山网络实习生招聘笔试题(2014-4-9)
- servlet在tomcat中读取文件问题
- file globbing(文件名替换)
- MVC design pattern in our project, the Order system
- 解决Unable to resolve target 'android-7'报错