gpt4 book ai didi

linq - 为什么在 foreach 中需要一个临时变量才能包含在 lambda 表达式中?

转载 作者:行者123 更新时间:2023-12-05 00:00:38 26 4
gpt4 key购买 nike

我在看 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;
}

在代码之后有一个“警告”,如下所示:
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

有人可以澄清一下吗?

最佳答案

因为只有一个变量叫 keyword那是关闭的。然而,临时变量每次迭代都不同。

因此,在没有临时变量的情况下,当稍后执行 lambda 时,keyword计算为它在循环中分配的最后一个值。

在某些情况下,另一种解决方案是强制评估(最终得到 List 或类似的结果)。

关于linq - 为什么在 foreach 中需要一个临时变量才能包含在 lambda 表达式中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9856005/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com