88장 반복기(Iterator)
Iterator 이란 ? |
Program.cs |
using System;
public class 반복기
{
public static void Main()
{
int[] data = { 1, 2, 3 };
foreach (var item in data)
{
Console.WriteLine(item);
}
Car hyundai = new Car(3);
hyundai[0] = "에쿠스";
hyundai[1] = "제네시스";
hyundai[2] = "그랜져";
for (int i = 0; i < hyundai.Length ; i++)
{
Console.WriteLine(hyundai[i]);
}
//Iterator
foreach (var item in hyundai)
{
Console.WriteLine(item);
}
}
}
Car.cs
using System;
public partial class Car
{
public int Length { get; set; }
private string[] names;
public Car(int length)
{
this.Length = length;
names = new string[length];
}
public string this[int index]
{
get{ return names[index];}
set{ names[index] = value;}
}
//반복기 구현
// GetEnumerator 메서드 : 제네릭이 아닌 컬렉션을 단순하게 반복할때 사용
public System.Collections.IEnumerator GetEnumerator()
{
for (int i = 0; i < names.Length; i++)
{
//나열하다
yield return names[i];
}
}
}
반복기 사용시 반드시 외워야 할 문법이라고 생각하고 외우면 됩니다.
//반복기 구현 // GetEnumerator 메서드 : 제네릭이 아닌 컬렉션을 단순하게 반복할때 사용 public System.Collections.IEnumerator GetEnumerator() { for (int i = 0; i < names.Length; i++) { //나열하다 yield return names[i]; } } } |
반복기 관련 참고사항
http://msdn.microsoft.com/ko-kr/library/65zzykke(VS.80).aspx |