IEnumerable 인터페이스의 메소드인 GetEnumerator()를 구현하면 foreach문을 사용할 수 있는 객체를 만들 수 있다.

class MyEnumerator : IEnumerable
{
    private string[] arr = {"a", "b", "c", "d"};
        
    public IEnumerator GetEnumerator()
    {
        yield return arr[0]+"_postfix";
        yield return arr[1]+"_postfix";
        yield return arr[2]+"_postfix";
        yield break;
        yield return arr[3];
    }
}
    
class MainApp
{
    static void Main(string[] args)
    {
        MyEnumerator obj = new MyEnumerator();
        foreach (var item in obj)
        {
            Console.WriteLine(item);
        }
    }        
}

/*
a_postfix
b_postfix
c_postfix
*/

 

IEnumerator의 Current 프로퍼티, MoveNext() 메소드와 Reset() 메소드를 구현하여 반복문을 사용할 수 있는 객체를 만들 수 있다.

class MyList : IEnumerator
{
    private int[] arr;
    private int position = -1;

    public MyList(int length)
    {
        arr = new int[length];
    }

    public int this[int index]
    {
        get => arr[index];
        set
        {
            if (index >= arr.Length)
            {
                Array.Resize(ref arr, index + 1);
            }

            arr[index] = value;
        }
    }

    public object Current => arr[position];

    public bool MoveNext()
    {
        if (position == arr.Length - 1)
        {
            Reset();
            return false;
        }

        position++;
        return position < arr.Length;
    }

    public void Reset()
    {
        position = -1;
    }
}
    
class MainApp
{
    static void Main(string[] args)
    {
        MyList list = new MyList(0);
        for (int i = 0; i < 5; i++)
            list[i] = i;

        while (list.MoveNext())
        {
            Console.WriteLine(list.Current);
        }
    }
}

'c#' 카테고리의 다른 글

인덱서  (0) 2021.04.16
c# Auto properties  (0) 2021.04.15
가변길이 매개변수 params  (0) 2021.04.14
c# out 키워드 두 개 이상의 결과를 내보낼 때 사용  (0) 2021.04.13
c# ref return  (0) 2021.04.13

+ Recent posts