为什么这个类不需要实现IEnumerable?

Moh*_*sen -5 c#

对于能够使用" foreach " 进行迭代的类,它应该实现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);
    }
}
Run Code Online (Sandbox Code Playgroud)

当我运行代码时,我没有得到关于使用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);
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

为什么?

Abh*_*hek 8

您正在使用List<T>类来存储您的PersonCollection,其中TPersonclass.在List<T>类实现IEnumerable接口.因此,您可以使用foreach