클래스를 열거

foreach 루프를 사용하여 클래스를 열거할 수 있도록 이 인터페이스를 구현한다.

인터페이스에는 컬렉션에 대한 열거자를 반환해야 하는 GetEnumerator() 메서드의 구현이 필요하다.

public class MyEnumerable : IEnumerable<int>
{
    private int[] data;

    public MyEnumerable(int[] data)
    {
        this.data = data;
    }

    public IEnumerator<int> GetEnumerator()
    {
        return data.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

이 예에서 MyEnumerable 클래스는 데이터를 열거할 수 있도록 IEnumerable 인터페이스를 구현합니

다. GetEnumerator 메서드는 컬렉션에 대한 열거자를 반환합니다.