針對一類能夠使用「的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 –