【发布时间】:2010-07-06 22:05:32
【问题描述】:
可能的重复:
Why is it bad to use a iteration variable in a lambda expression
C# - The foreach identifier and closures
来自Eric Lippert's 28 June 2010 入口:
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;
}
var s = sequence; 看起来像一个空操作。为什么不是一个?直接使用sequence会出现什么问题?
而且,更主观地说:这在多大程度上被认为是 C# 行为的缺陷?
【问题讨论】:
-
这个问题在stackoverflow.com/questions/227820stackoverflow.com/questions/2717377stackoverflow.com/questions/566687stackoverflow.com/questions/451779stackoverflow.com/questions/451779stackoverflow.com/questions/304258stackoverflow.com/questions/235455stackoverflow.com/questions/2951037stackoverflow.com/questions/1688465@98765433333329之前已经被问和解释了1000次
-
嗯,我不知道这个,很高兴已经有一百万个线程。