在这个答案中,https: //stackoverflow.com/a/8649429/1497 Eric Lippert说"我们很有可能在下一版本的C#中解决这个问题;对于开发人员而言,这是一个主要的痛点". foreach循环使用变量.
在下一个版本中,每次运行"foreach"循环时,我们将生成一个新的循环变量,而不是每次都关闭相同的变量.这是一个"突破"的变化,但在绝大多数情况下,"休息"将是修复而不是导致错误.
我无法找到任何表明此更改尚未完成的内容.有没有迹象表明这是foreach循环在C#5中的工作方式?
下面给出了VS 2010中的1和VS 2012中的2的答案.我个人认为它应该是2.我不确定这里发生了什么.
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System;
namespace _335ExamPreparation
{
public class Doubts
{
int[] nums = { 10, 11, 12, 13, 14, 15, 16 };
int[] divisors = { 7, 10 };
static void Main(string[] args)
{
Doubts d = new Doubts();
d.func();
}
public void func()
{
var m = Enumerable.Empty<int>();
foreach (int d in divisors)
{
m = m.Concat(nums.Where(s => (s % d == 0)));
}
int count = m.Distinct().Count();
Console.WriteLine(count);
}
} …Run Code Online (Sandbox Code Playgroud)