简体   繁体   English

访问Lambda表达式中的Modified Closure

[英]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)));
}

It tells you that the "category" variable lives in closure and can be modified outside your LINQ expression. 它告诉您“类别”变量存在于闭包中,可以在LINQ表达式之外进行修改。

Look at the question here for some explanation. 这里查看问题以获得一些解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM