==>  반복기.cs



// Iterator : 내가 만든 객체를 foreach문으로
// 돌리고자할 때 반복기가 구현되어있어야 함..

using System;

public class 반복기
{
    public static void Main()
    {
        int[] data = {1, 2, 3 };
        foreach (var item in data)
        {
            Console.WriteLine(item);
        }
        Car hyundai; // Class
        hyundai = new Car(3); // Constructor
        hyundai[0] = "에쿠스"; // Indexer
        hyundai[1] = "제네시스";
        hyundai[2] = "그랜져";
        // Length Property

        for (int i = 0; i < hyundai.Length; i++)
        {
            Console.WriteLine(hyundai[i]);
        }

        // Iterator
        foreach (var item in hyundai)
        {
            Console.WriteLine(item);
        }
    }

}




==============================================================================================



==> Car.cs



using System;

public partial class Car
{
    public int Length { get; set; }
    private string[] names;
    public Car(int length)
    {
        this.Length = length;
        names = new string[length];
    }
    public string this[int index]
    {
        get { return names[index]; }
        set { names[index] = value; }
    }

    // Iterator : 반복기 : GetEnumerator
    public System.Collections.IEnumerator GetEnumerator()
    {
        for (int i = 0; i < names.Length; i++)
        {
            yield return names[i];
        }
    }
}


/*
yield : 나열하다

foreach문은 GetEnumerator함수를 호출한다.

'GetEnumerator()메서드'의 반환값은 'IEnumerator인터페이스'이다.
*/

Posted by holland14
: