Language/C#
[C#] IEnumerable 과 IEnumerator 의 쓰임새
RAY.D
2015. 4. 28. 15:36
다음 코드 예제에서는 IEnumerable 및 IEnumerator 인터페이스를 구현하여 사용자 정의 컬렉션을 반복하는 데 가장 좋은 방법을 보여줍니다. 이 예제에서 이러한 인터페이스의 멤버는 명시적으로 호출되지 않지만 foreach(Visual Basic의 경우 For Each)를 사용하여 컬렉션을 반복하는 것을 지원하기 위해 구현됩니다.
IEnumerable 인터페이스를 구현하는 방법에 대한 예제는 컬렉션 클래스에 IEnumerable 인터페이스의 구현 을 참조하십시오.
주) 즉, 개발자가 Class를 만들때 이 class가 사용자 정의 컬렉션 이며 foreach 를 쓰고 싶으면 IEnumerable 과 IEnumerator 인터페이스에서 정의된 메소드들을 구현하여야 한다
using System; using System.Collections; public class Person { public Person(string fName, string lName) { this.firstName = fName; this.lastName = lName; } public string firstName; public string lastName; } public class People : IEnumerable { private Person[] _people; public People(Person[] pArray) { _people = new Person[pArray.Length]; for (int i = 0; i < pArray.Length; i++) { _people[i] = pArray[i]; } } IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator) GetEnumerator(); } public PeopleEnum GetEnumerator() { return new PeopleEnum(_people); } } public class PeopleEnum : IEnumerator { public Person[] _people; // Enumerators are positioned before the first element // until the first MoveNext() call. int position = -1; public PeopleEnum(Person[] list) { _people = list; } public bool MoveNext() { position++; return (position < _people.Length); } public void Reset() { position = -1; } object IEnumerator.Current { get { return Current; } } public Person Current { get { try { return _people[position]; } catch (IndexOutOfRangeException) { throw new InvalidOperationException(); } } } } class App { static void Main() { Person[] peopleArray = new Person[3] { new Person("John", "Smith"), new Person("Jim", "Johnson"), new Person("Sue", "Rabon"), }; People peopleList = new People(peopleArray); foreach (Person p in peopleList) Console.WriteLine(p.firstName + " " + p.lastName); } } /* This code produces output similar to the following: * * John Smith * Jim Johnson * Sue Rabon * */