在这个答案中 https://stackoverflow.com/a/8649429/1497关于 foreach 循环如何使用变量,Eric Lippert 说“仅供引用,我们很可能在下一版本的 C# 中修复此问题;这是开发人员的主要痛点”。
In the next version each time you run through the "foreach" loop we will generate a new loop variable rather than closing over the same variable every time. This is a "breaking" change but in the vast majority of cases the "break" will be fixing rather than causing bugs.
我还没有找到任何表明已进行此更改的信息。是否有迹象表明这就是 foreach 循环在 C# 5 中的工作方式?
最佳答案
这是对 C# 语言的更改,而不是对 .NET 框架的更改。因此,它只影响在 C# 5.0 下编译的代码,而不管该代码将在哪个 .NET Framework 版本上执行。
C# 5.0
规范的第 8.8.4 节明确表示已进行此更改。具体来说,C# 5.0 规范的第 249 页指出:
foreach (V v in x) embedded-statement
is then expanded to:
{
E e = ((C)(x)).GetEnumerator();
try {
while (e.MoveNext()) {
V v = (V)(T)e.Current;
embedded-statement
}
}
finally {
… // Dispose e
}
}
之后:
The placement of v inside the while loop is important for how it is captured by any anonymous function occurring in the embedded-statement.
C# 4.0
与 C# 4.0 规范相比,规范的这一变化是显而易见的,该规范指出(再次在第 8.8.4 节中,但这次是第 247 页):
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
}
}
请注意,变量 v
是在循环外声明的,而不是在循环内声明的,就像在 C# 5.0 中一样。
注意事项
您可以在 VC#\Specifications\1033
下的 Visual Studio 安装文件夹中找到 C# 规范。 VS2005、VS2008、VS2010 和 VS2012 就是这种情况,您可以访问 C# 1.2、2.0、3.0、4.0 和 5.0 的规范。您还可以通过搜索 C# Specification
在 MSDN 上找到规范。
关于c# - foreach 对变量的使用是否在 C# 5 中发生了变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12112881/