728x90
반응형
[예제1] 프로그램 출발 코드 (유도과정 1)
1. foreach는 GetEnumerator함수를 호출한다.
return 100;은 var item in a
2. 내가 만든 클래스 A를 foreach문에 사용하고 싶다.
3. foreach문을 걸어 보니까 객체를 모른다는 에러가 뜬다.
4. 에러내용: foreach문을 사용하고 싶으면 GetEnumerator함수를 구현해야 한다.
5. 함수를 구현하고 나니까 에러가 사라진다.
6. 리턴값이 필요하기 때문에 return을 걸기는 했지만, 반드시 yield return 사용.
7. foreach와 yield return을 이용해서 반복구조를 만들라고 하는것이 권유사항.
8. yield return을 사용하지 않고 foreach를 성립시키는 프로그램 방법이 있다.
9. 그 방법은 IEnumerable, IEnumerator을 상속받아서 처리한다.
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
namespace ConsoleApp1
{
class Program
{
class A
{
int[] ar = { 10, 20, 30, 40, 50 };
public IEnumerator GetEnumerator()
{
// yield 키워드가 있어야 한다.
for (int i = 0; i < ar.Length; i++)
{
yield return ar[i];
}
}
}
static void Main(string[] args)
{
A a = new A();
foreach (var item in a)
{
WriteLine(item);
}
}
}
}
// 출력값 : 10 20 30 40 50
[예제2] (유도과정 2)
1. 표준 인터페이스 상속을 받는다.
2. 단축키를 이용하여 인터페이스를 구현한다.
3. 적당하게 코드를 수정한다.
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
namespace ConsoleApp1
{
class Program
{
class A : IEnumerable, IEnumerator
{
int[] ar = { 10, 20, 30, 40, 50 };
public object Current
{
get { return 100; } // get { return ar[]; }
}
public IEnumerator GetEnumerator()
{
WriteLine("GetEnumerator");
return null;
}
public bool MoveNext()
{
throw new NotImplementedException();
}
public void Reset()
{
throw new NotImplementedException();
}
}
static void Main(string[] args)
{
A a = new A();
foreach(var item in a)
{
WriteLine(item);
}
}
}
}
[예제3]
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
namespace ConsoleApp1
{
class Program
{
class A : IEnumerable, IEnumerator
{
int[] ar = { 10, 20, 30, 40, 50 };
public object Current
{
get
{
WriteLine("Current");
// ar[pos]값이 foreach의 item으로 리턴된다.
return ar[pos]; } // get { return ar[]; }
}
public IEnumerator GetEnumerator()
{
WriteLine("GetEnumerator");
// this를 리턴하면 무조건 MoVeNext()함수를 call하게 된다.
return this;
}
int pos = -1;
public bool MoveNext()
{
// pos == 4면 반복종료
if (pos == ar.Length - 1)
{
WriteLine("End Looping");
return false;
}
WriteLine("MoveNext");
pos++;
// true일때 Current를 사용한다.
return pos < ar.Length; // 반복이 끝나지 않음
//return false; // 반복이 끝남
}
public void Reset()
{
pos = -1;
}
}
static void Main(string[] args)
{
A a = new A();
foreach(var item in a)
{
WriteLine(item);
}
}
}
}
728x90
반응형
'Education > Edu | .net' 카테고리의 다른 글
# 29.1) [C#] 문법12 (delegate) (0) | 2021.02.24 |
---|---|
# 28.2) [C#] 문법11 (Generic) (0) | 2021.02.23 |
[C# 언어 3강] 데이터형 (5/5) 값 형식과 참조 형식, 정리 (0) | 2021.02.23 |
# 27) [C#] 문법9 (array) (0) | 2021.02.22 |
# 26.3) [C#] 문법8 (Property) (0) | 2021.02.19 |