从埃里克利珀的博客:"不要关闭了循环变量" [英] From Eric Lippert's blog: "don't close over the loop variable"
问题描述
可能显示的文件:结果
<一href=\"http://stackoverflow.com/questions/227820/why-is-it-bad-to-use-a-iteration-variable-in-a-lambda-ex$p$pssion\">Why它是坏的使用迭代变量的lambda前pression 结果
C# - 在foreach标识符和关闭
从<一个href=\"http://blogs.msdn.com/b/ericlippert/archive/2010/06/28/computing-a-cartesian-product-with-linq.aspx\"相对=nofollow>埃里克利珀的28 2010年6月作品:
static IEnumerable<IEnumerable<T>>
CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences)
{
// base case:
IEnumerable<IEnumerable<T>> result = new[] { Enumerable.Empty<T>() };
foreach(var sequence in sequences)
{
var s = sequence; // don't close over the loop variable
// recursive case: use SelectMany to build the new product out of the old one
result =
from seq in result
from item in s
select seq.Concat(new[] {item});
}
return result;
}
的变种S =序列;
看起来像一个空操作。为什么不是呢?有什么不顺心的时候序
直接使用?
The var s = sequence;
looks like a no-op. Why isn't it one? What goes wrong when sequence
is used directly?
和,更主观:在何种程度上这被认为是在C#的行为疣
And, more subjectively: to what extent is this considered a wart in C#'s behaviour?
推荐答案
一对夫妇从埃里克本人相关的文章,在评论一些有趣的讨论,一起:
A couple of relevant articles from Eric himself, along with some interesting discussion in the comments:
- 关闭了被认为是有害 循环变量
- 关闭了循环变量,第二部分
- Closing over the loop variable considered harmful
- Closing over the loop variable, part two
这篇关于从埃里克利珀的博客:&QUOT;不要关闭了循环变量&QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!