[英]Access to Modified Closure in Lambda Expression
foreach(var category in categories) {
a.AddRange(_db.Articles.Where(c => c.Categories.Contains(category)));
}
The code runs fine, yet I get a warning about "access to modified closure" in reference to category
used in the lambda expression. 代码运行正常,但我在引用lambda表达式中使用的category
收到关于“访问修改后的闭包”的警告。
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. 这里的警告是因为您正在访问Where
lambda的闭包内的变量category
。 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. 值category
随每次迭代而变化, Where
延迟执行,因此它将看到category
的当前值与创建lambda时的值。
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. 即使Where
进行延迟评估, AddRange
方法仍然是提示,并将强制评估Where
完成。 Hence the Where
method will see the value of category
it expects. 因此Where
方法将看到它期望的category
的值。
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)));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.