MSDN의이 예의 경우 GetEnumerator
메서드에서 PeopleEnum
은 IEnumerator
을 반환합니까?GetEnumerator 메서드에서이 예제에서 (get from msdn) 이유는 새로운 PeopleEnum이 IEnumerator를 반환합니까?
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];
}
}
//why???
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();
}
}
}
UPDATE : 배열 데이터 타입이 ICloneable 인터페이스를 구현하는 경우 BTW, 왜 MSDN은 루프를 작성하여 _people하는 pArray 복사했다?
사실, 여기 * 아무것도 * 않는 것은 놀라운 일이다 - 그것은 또한 단지 (IEnumerator''로) 수'_people.GetEnumerator() 반환;' –
@Marc을 : 또는 그 문제에 관해서는 파생 수 콜렉션 :) –
Josh
@Josh - 1.1 예제처럼 보입니다. –