根据Eric Lippert 博客和规范,foreach 循环是一种语法糖:
{
IEnumerator<string> e = ((IEnumerable<string>)new string[] { "pass1", "pass2", "pass3" }).GetEnumerator();
try
{
string pass; // OUTSIDE THE ACTUAL LOOP
while(e.MoveNext())
{
pass = (string)e.Current;
x = pass;
}
}
finally
{
if (e != null) ((IDisposable)e).Dispose();
}
}
如您所见,枚举器是在循环之前创建的。
@Rawling 正确指出,编译器对该数组的处理略有不同。Foreach循环被优化为带有数组的 for循环。根据The Internals of C# foreach您的 C# 5 代码将如下所示:
string[] tempArray;
string[] array = new string[] { "pass1", "pass2", "pass3" };
tempArray = array;
for (string counter = 0; counter < tempArray.Length; counter++)
{
string pass = tempArray[counter];
x = pass;
}
初始化也只发生一次。