Access to Modified Closure in Lambda Expression

混江龙づ霸主 提交于 2019-12-12 12:25:30

问题


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.

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


回答1:


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.

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)));
}



回答2:


It tells you that the "category" variable lives in closure and can be modified outside your LINQ expression.

Look at the question here for some explanation.



来源:https://stackoverflow.com/questions/9186189/access-to-modified-closure-in-lambda-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!