【发布时间】:2012-01-09 15:47:40
【问题描述】:
为什么我必须创建IEnumerable<T> 的具体实现才能在foreach 循环中修改其成员?
This blog post (Exhibit 1) 解释了这种行为,但我无法完全理解它。
我在这里有一个非常简单的代码 sn-p 来重现该问题(C# 4.0 / .NET 4.0)。
class Person
{
public int Age { get; set; }
public Person()
{
}
}
class Program
{
static void Main(string[] args)
{
//calling .ToList() on GetPeople() below will fix the issue
var people = GetPeople();
foreach (var item in people)
{
item.Age = DateTime.Now.Second;
}
foreach (var item in people)
{
Console.WriteLine("Age is {0}", item.Age);
}
Console.Read();
}
public static IEnumerable<Person> GetPeople()
{
int i = 0;
while (i < 3)
{
i++;
yield return new Person();
}
}
}
【问题讨论】:
标签: c# c#-4.0 foreach ienumerable