프로그래밍/C#

[C#] IEnumerable , IEnumerator 인터페이스

QA Engineer - P군 2016. 9. 29. 10:31
반응형

 

IEnumerable

컬렉션을 반복하는 열거자를 반환합니다.
컬렉션을 반복하는 데 사용할 수 있는 System.Collections.IEnumerator 개체를 반환합니다.

인테페이스 이므로 다음과 같은 형식의 메서드를 반드시 정의해야합니다.

 

메서드   설명 
 IEnumerator GetEnumerator();  요약:
    컬렉션을 반복하는 열거자를 반환합니다.


반환 값: 
    컬렉션을 반복하는 데 사용할 수 있는         System.Collections.IEnumerator 개체입니다.
 

 IEnumerator

제네릭이 아닌 컬렉션을 단순하게 반복할 수 있도록 지원합니다.
Current 을 통해 컬렉션 요소를 반환하고 MoveNext()을 통해서 반복을 지원합니다.
IEnumerable 를 사용하는데 사용하는 인터페이스 입니다.
인테페이스 이므로 다음과 같은 메서드를 반드시 정의해야합니다.

 

 메서드   설명 
 object Current { get; }  요약:
    컬렉션의 현재 요소를 가져옵니다.


반환 값:
    컬렉션의 현재 요소입니다.
 bool MoveNext();  요약:
    열거자를 컬렉션의 다음 요소로 이동합니다.


반환 값:
    열거자가 다음 요소로 이동한 경우 true가 반환되고, 컬렉션의 끝을 지난 경우 false가 반환됩니다.


예외:
  System.InvalidOperationException:
    열거자가 만들어진 후 컬렉션이 수정된 경우
 void Reset();  요약:
    컬렉션의 첫 번째 요소 앞의 초기 위치에 열거자를 설정합니다.


예외:
  System.InvalidOperationException:
    열거자가 만들어진 후 컬렉션이 수정된 경우

[예제]


[Item Class] - 반환 단위

public class Item
{
    public Item(string _name, int _price)
    {
        this.itemName = _name;
        this.price = _price;
    }
              
    public string itemName;
    public int price;
}

[IEnumerable Class] - 열거자 반환 (아이템 반환)

public class Shop : IEnumerable
{
    private Item[] _item;

    public Shop(Item[] pArray)
    {
        _item = new Item[pArray.Length];
                  
        for (int i = 0; i < pArray.Length; i++)
        {
            _item[i] = pArray[i];
        }
    }

    //GetEnumerator 메서드 구현
    IEnumerator IEnumerable.GetEnumerator()
    {                  
        return (IEnumerator)GetEnumerator();
    }

    public ItemEnum GetEnumerator()
    {
        return new ItemEnum(_item);
    }
}

[IEnumerator Class] - 반복 지원

public class ItemEnum : IEnumerator
{
    public Item[] _item;

    int position = -1;
     
    // 생성자
    public ItemEnum(Item[] list)
    {
        _item = list;
    }

    // IEnumerator Current 구현
    object IEnumerator.Current
    {
        get { return Current; }
    }
    
    public Item Current
    {
        get
        {
            try
            {
                return _item[position];
            }
            catch (IndexOutOfRangeException)
            {
                throw new InvalidOperationException();
            }
        }
    }
    
    // IEnumerator MoveNext 구현
    public bool MoveNext()
    {
        position++;
        return (position < _item.Length);
    }

    // IEnumerator Reset 구현
    public void Reset()
    {
        position = -1;
    }
}

[실행]

 

 

static void Main(string[] args)
{
    // 아이템 생성
    Item[] itmeArray = new Item[3]
    {
        new Item("검", 1000),
        new Item("방패", 2000),
        new Item("갑옷", 3000),
    };

    // 상점에 아이템 등록
    Shop itemList = new Shop(itmeArray);

    // foreach 문을 통해서 반복해서 출력
    foreach (Item item in itemList)
        Console.WriteLine(item.itemName + " " +item.price);
}

[결과]

 

 

[참고]

IEnumerable  [MSDN]

https://msdn.microsoft.com/ko-kr/library/system.collections.ienumerable.aspx

 

IEnumerator [MSDN]

https://msdn.microsoft.com/en-us/library/system.collections.ienumerator(v=vs.110).aspx

반응형