.Net Project/.Net C#

88장 반복기(Iterator)

래곤 2009. 8. 17. 16:16
반응형

Iterator 이란 ?  
명명된 반복기를 사용하면 동일한 데이터 컬렉션을 각기 다른 방법으로 반복할 수도 있습니다. 예를 들어, 요소를 오름차순으로 반환하는 반복기와 요소를 내림차순으로 반환하는 반복기를 지정할 수 있습니다. 반복기에 매개 변수를 사용하여 클라이언트에서 반복기의 동작 전체 또는 일부를 제어할 수도 있습니다.
다음 반복기는 SampleIterator라는 명명된 반복기를 사용하여 IEnumerable
인터페이스를 구현합니다.


 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

 

반응형