열거자를 사용하기 위한 방법이다.
1. IEnumerator를 상속 받는 방법..
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IEnumeratorTest { class myEnumerator : IEnumerator { string[] whoareyou; int position = -1; public object Current { get { return whoareyou[position]; } } public bool MoveNext() { if (position < whoareyou.Length - 1) { position++; return true; } else return false; } public void Reset() { position = -1; } public myEnumerator(string[] inNames) { whoareyou = new string[inNames.Length]; for (int i = 0; i < inNames.Length; i++) whoareyou[i] = inNames[i]; } } }
종류 |
유형 |
기능 |
Current |
속성 |
읽기 전용 속성으로 현재 위치의 아이템을 object로 반환 |
MoveNext |
메서드 |
다음 위치로 이동, 다음 아이템 존재 true, 아니면 false |
Reset |
메서드 |
초기 상태로 위치를 설정 |
2. IEnumerator<T>를 상속 받는 방법.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IEnumeratorTest { class genericEnumerator : IEnumerator<string> { string[] strPlayer; int position = -1; public string Current { get { return strPlayer[position]; } } public void Dispose() { } object System.Collections.IEnumerator.Current { get { return strPlayer[position]; } } public bool MoveNext() { if (position < strPlayer.Length - 1) { position++; return true; } else return false; } public void Reset() { position = -1; } public genericEnumerator(string[] inNames) { strPlayer = new string[inNames.Length]; for (int i = 0; i < inNames.Length; i++) { strPlayer[i] = inNames[i]; } } } }
종류 |
유형 |
기능 |
Current |
속성 |
IEnumerator로 부터 상속된 속성 현재 위치의 아이템을 Object로 반환 |
Current |
속성 |
T Current {get;}의 형태로 T로 반환 |
Dispose | 메서드 | 파일 스트림과 같은 관리되지 않는 자원을 닫거나 해제할 때 사용 |
MoveNext |
메서드 |
다음 위치로 이동, 다음 아이템이 있으면 true 없으면 false |
Reset |
메서드 |
초기 위치로 설정 |
Main
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IEnumeratorTest { class Program { static void Main(string[] args) { myEnumerator my = new myEnumerator(new string[] { "전우치", "홍길동", "머털도사" }); while (my.MoveNext()) { string strName = (string)my.Current; Console.WriteLine("{0}", strName); } genericEnumerator str = new genericEnumerator(new string[] { "베트맨", "슈퍼맨", "아이언맨" }); while (str.MoveNext()) { string strName = (string)str.Current; Console.WriteLine("{0}", strName); } Console.ReadLine(); } } }
'Functional World > C#' 카테고리의 다른 글
바이트 배열 취득 (0) | 2013.10.01 |
---|---|
boxing 에 대한 생각의 오류.... (0) | 2013.09.30 |
Generic Collections (0) | 2013.07.15 |
C# 5.0 async, await (0) | 2013.07.05 |
Runtime에 클래스 맴버를 취득 하고자 할 경우…. (0) | 2013.07.04 |