针对一类能够使用“的foreach”进行迭代,它应该实现的IEnumerable接口。 但为什么这个没有实现的简单类可以迭代?为什么这个类不需要实现IEnumerable?
public class Person
{
public int Age { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Person() { }
public Person(string firstName, string lastName, int age)
{
Age = age;
FirstName = firstName;
LastName = lastName;
}
public override string ToString()
{
return string.Format("Name: {0} {1}, Age: {2}",
FirstName, LastName, Age);
}
}
当我运行的代码,我得到使用的foreach
class Program
{
static void Main(string[] args)
{
UseGenericList();
}
static void UseGenericList()
{
List<Person> people=new List<Person>()
{
new Person("Homer","Simpson",47),
new Person {FirstName = "Marge",LastName ="Simpson",Age = 45},
new Person {FirstName = "Lisa",LastName = "Simpson",Age = 9},
new Person {FirstName = "Bart",LastName = "Simpson",Age = 8}
};
Console.WriteLine("Items in the list:{0}",people.Count);
foreach (Person P in people)
{
Console.WriteLine(P);
}
Console.WriteLine("Inserting new person");
people.Insert(2,new Person {FirstName ="Maggie",LastName = "Simpson",Age = 2});
Console.WriteLine("items in the list{0}",people.Count);
Person[] ArraysOfPeople = people.ToArray();
for (int i = 0; i < ArraysOfPeople.Length; i++)
{
Console.WriteLine("First Name:{0}",ArraysOfPeople[i].FirstName);
}
}
}
关于为什么没有错误?
因为您正在迭代'List',您**不是**迭代'Person'。迭代人看起来像'foreach(var personObjectObject)',当然它会失败 –
列表实现IEnumerable –