进入修改封闭在Lambda表达式 [英] Access to Modified Closure in Lambda Expression

查看:121
本文介绍了进入修改封闭在Lambda表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

foreach(var category in categories) {
    a.AddRange(_db.Articles.Where(c => c.Categories.Contains(category)));
}



中的代码运行正常,但我得到一个关于获得修改封警告参照类别中的lambda表达式中使用

The code runs fine, yet I get a warning about "access to modified closure" in reference to category used in the lambda expression.

问:是在这种情况下任何后果的警告?

Question: Is the warning of any consequence in this circumstance?

推荐答案

这里的警告是因为你要访问的变量类别关闭了其中,拉姆达内。该值类别与每次迭代变化和其中,是执行,因此它会看到的当前值延迟类别与在拉姆达创建时的价值。

The warning here is because you are accessing the variable category inside the closure for the Where lambda. The value category changes with every iteration and Where is delay executed hence it will see the current value of category vs. the value at the time the lambda was created.

在这种情况下,你可能罚款。尽管其中,被延迟评估的AddRange 方法是及时和将迫使的评价在哪里完成。因此,其中,方法将看到类的值预计。

In this case you are likely fine. Even though Where is delay evaluated the AddRange method is prompt and will force the evaluation of Where to completion. Hence the Where method will see the value of category it expects.

如果你想删除警告,虽然只是声明迭代变量的本地副本和捕获的替代。

If you'd like to remove the warning though simply declare a local copy of the iteration variable and capture that instead.

foreach(var category in categories) {
  var localCategory = category;
  a.AddRange(_db.Articles.Where(c => c.Categories.Contains(localCategory)));
}

这篇关于进入修改封闭在Lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆