如果我用 C# 编写一个 foreach 语句:
foreach(String a in veryComplicatedFunction())
{
}
它会在每次迭代或只计算一次 veryComplicatedFunction 并将其存储在某个地方吗?
最佳答案
您的问题已在 12.9.5 部分得到解答规范,其中规定:
The above steps, if successful, unambiguously produce a collection type C, enumerator type E and element type T. A foreach statement of the form
foreach (V v in x) embedded-statement
is then expanded to:
{
E e = ((C)(x)).GetEnumerator();
try {
V v;
while (e.MoveNext()) {
v = (V)(T)e.Current;
embedded-statement
}
}
finally {
… // Dispose e
}
}
如您所见,在展开式中,表达式 x 仅被求值一次。
关于c# - C# 中的 foreach 重新计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1517686/