c#
IEnumerable과 IEnumerator
fd27
2021. 4. 16. 10:23
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);
}
}
}