为什么foreach中需要的临时变量包含在lambda表达式中?

seb*_*mez 4 linq lambda iqueryable c#-4.0

我正在阅读C# 4 in a Nutshell,我来到这段代码:

IQueryable<Product> SearchProducts (params string[] keywords)
{
  IQueryable<Product> query = dataContext.Products;

  foreach (string keyword in keywords)
  {
    string temp = keyword;
    query = query.Where (p => p.Description.Contains (temp));
  }
  return query;
}
Run Code Online (Sandbox Code Playgroud)

在代码之后有一个"警告",如下所示:

The temporary variable in the loop is required to avoid the outer variable trap, where the same variable is captured for each iteration of the foreach loop.

我不明白,我不明白为什么temp变量是必要的.什么是outter variable trap

来自:http://www.albahari.com/nutshell/predicatebuilder.aspx

有人可以澄清一下吗?

小智 5

因为只有一个被调用的变量keyword被关闭.但是,临时变量在每次迭代时都是不同的.

因此,如果没有临时变量,则稍后执行 lambda时,将keyword计算它在循环中分配的最后一个值.

在某些情况下,另一种解决方案是强制进行评估(最终得到一个List或那样).