foreach 문은 IEnumerable, Enumerator 를 상속하는 형식만 지원한다.
IEnumerable의 메소드
IEnumerator GetEnumerator() : IEnumerator 형식의 객체를 반환
IEnumerator의 메소드
boolean MoveNext() : 다음 요소로 이동. 컬렉션 끝을 지난 경우에는 false, 이동이 성공한 경우에는 true
void Reset() : 컬렉션 첫번째 위치의 앞으로 이동. (-1)
Object Current { get; } : 컬렉션의 현재 요소 반환.
class MyList : IEnumerable, IEnumerator{
private int[] array;
int position = -1;
public MyList(){
array = new int[3];
}
public int this[int index]{
get{ return array [index]; }
set{
if (index >= array.Length) {
Array.Resize<int> (ref array, index + 1);
Console.WriteLine ("Array Resized : {0}", array.Length);
}
array[index] = value;
}
}
public object Current{
get{ return array [position]; }
}
public bool MoveNext(){
if (position == array.Length - 1) {
Reset ();
return false;
}
position++;
return (position < array.Length);
}
public void Reset(){
position = -1;
}
public IEnumerator GetEnumerator(){
for (int i = 0; i < array.Length; i++) {
yield return (array [i]);
}
}
}
댓글