게임 개발/개발 공부
[ 개발 공부 ] IEnumerator, IEnumerable
ksan09
2024. 5. 15. 16:00
IEnumerator는 다른 언어의 Iterator와 비슷한 역할을 하는 열거자입니다.
IEnumerator를 알기 위해 IEnumerable부터 알아봅시다.
IEnumerable은 인터페이스입니다.
이 때 IEnumerable라는 인터페이스는 IEnumerator를 반환하는 GetEnumerator라는 메서드를 구현해야 합니다.
public class SceneTitle : IEnumerable
{
private string[] _titles = ["Intro", "Play", "Ending"];
// IEnumerable 인터페이스를 구현
public IEnumerator GetEnumerator()
{
for (int index = 0; index < _titles.Length; index++)
yield return _titles[index];
}
}
IEnumerable을 구현한 클래스는 foreach문으로 실행시킬 수 있습니다.
foreach문으로 실행할 때 GetEnumerator를 통해 반환한 순서대로 foreach문이 실행이 됩니다.
예를 들어
현재 상황에서 foreach문을 통해 텍스트를 차례대로 연결 시, IntroPlayEnding이 나옵니다.
yield return _titles[2] ~ _titles[0] 순서대로 했을 경우에는 EndingPlayIntro가 나옵니다.
IEnumerator는
이러한 방식으로 되어있는데,
foreach 문에서 MoveNext를 통해 Current를 다음 yield return 값으로 변경하는 작업을 수행합니다.