성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] 그냥 RSS Reader 기능과 약간의 UI 편의성 때문에 사용...
[이종효] 오래된 소프트웨어는 보안 위협이 되기도 합니다. 혹시 어떤 기능...
[정성태] @Keystroke IEEE의 문서를 소개해 주시다니... +_...
[손민수 (Keystroke)] 괜히 듀얼채널 구성할 때 한번에 같은 제품 사라고 하는 것이 아...
[정성태] 전각(Full-width)/반각(Half-width) 기능을 토...
[정성태] Vector에 대한 내용은 없습니다. Vector가 닷넷 BCL...
[orion] 글 읽고 찾아보니 디자인 타임에는 InitializeCompon...
[orion] 연휴 전에 재현 프로젝트 올리자 생각해 놓고 여의치 않아서 못 ...
[정성태] 아래의 글에 정리했으니 참고하세요. C# - Typed D...
[정성태] 간단한 재현 프로젝트라도 있을까요? 저런 식으로 설명만 해...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>C# - yield 문을 사용할 수 있는 메서드의 조건</h1> <p> 다음과 같은 질문이 있군요. ^^<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > yield return의 리턴 타입 질문드립니다. ; <a target='tab' href='http://www.sysnet.pe.kr/3/0/5156'>http://www.sysnet.pe.kr/3/0/5156</a> </pre> <br /> 우선, yield 문을 사용할 수 있는 메서드 조건은 문서에 잘 나와 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > yield (C# Reference) ; <a target='tab' href='https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/yield'>https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/yield</a> </pre> <br /> <ul> <li>반환 타입은 반드시 IEnumerable, IEnumerable<T>, IEnumerator, IEnumerator<T> 중의 하나여야 한다.</li> <li>메서드의 인자에는 in, ref, out 조건을 가질 수 없다.</li> </ul> <br /> 첫 번째 조건에 의해, C# 컴파일러는 yield 문이 사용된 메서드의 반환 형식이 IEnumerable이면 자동 생성되는 클래스를 IEnumerable과 IEnumerator를 함께 상속받도록 만듭니다. 반면 IEnumerator를 반환하는 메서드의 경우 IEnumerable은 필요 없으니 제외하고 IEnumerator만 구현합니다. <br /> <br /> 직접 확인해 볼까요? ^^ 본문(<a target='tab' href='http://www.sysnet.pe.kr/3/0/5156'>yield return의 리턴 타입 질문드립니다.</a>)에 실린 예제를 보면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > using System; using System.Collections; using System.Collections.Generic; public class NameSet : IEnumerable { private List<string> names = new List<string>(); public NameSet(params string[] values) { foreach (var e in values) this.names.Add(e); } <span style='color: blue; font-weight: bold'>public IEnumerable NameList()</span> { int currentIndex = 0; while (currentIndex < names.Count) { <span style='color: blue; font-weight: bold'>yield return</span> names[currentIndex]; currentIndex++; } } <span style='color: blue; font-weight: bold'>public IEnumerator GetEnumerator()</span> { int currentIndex = 0; while (currentIndex < names.Count) { <span style='color: blue; font-weight: bold'>yield return</span> names[currentIndex]; currentIndex++; } } } namespace ConsoleApp1 { class Program { static void Main(string[] args) { var names = new NameSet("abc", "def", "ghi"); <span style='color: blue; font-weight: bold'>foreach (var e in names.NameList())</span> Console.WriteLine(e); <span style='color: blue; font-weight: bold'>foreach (var e in names)</span> Console.WriteLine(e); } } } </pre> <a name='gen_class'></a> <br /> NameList 메서드의 경우 IEnumerable을 반환하므로 C# 컴파일러는 다음과 같은 식의 클래스를 생성해 줍니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > [CompilerGenerated] private sealed class <NameList>d__2 : <span style='color: blue; font-weight: bold'>IEnumerable<object>, IEnumerable, IEnumerator<object></span>, IDisposable, <span style='color: blue; font-weight: bold'>IEnumerator</span> { // Fields private int <>1__state; private object <>2__current; public NameSet <>4__this; private int <>l__initialThreadId; private int <currentIndex>5__1; // Methods [DebuggerHidden] public <NameList>d__2(int <>1__state); private bool MoveNext(); [DebuggerHidden] IEnumerator<object> IEnumerable<object>.GetEnumerator(); [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator(); [DebuggerHidden] void IEnumerator.Reset(); [DebuggerHidden] void IDisposable.Dispose(); // Properties object IEnumerator<object>.Current { [DebuggerHidden] get; } object IEnumerator.Current { [DebuggerHidden] get; } } </pre> <br /> 달리 말하면, NameList 메서드는 IEnumerable + IEnumerator가 구현된 클래스로 바뀌는 것입니다. 반면 IEnumerator를 반환하는 GetEnumerator 메서드는,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > [CompilerGenerated] private sealed class <GetEnumerator>d__3 : <span style='color: blue; font-weight: bold'>IEnumerator<object></span>, IDisposable, <span style='color: blue; font-weight: bold'>IEnumerator</span> { // Fields private int <>1__state; private object <>2__current; public NameSet <>4__this; private int <currentIndex>5__1; // Methods [DebuggerHidden] public <GetEnumerator>d__3(int <>1__state); private bool MoveNext(); [DebuggerHidden] void IEnumerator.Reset(); [DebuggerHidden] void IDisposable.Dispose(); // Properties object IEnumerator<object>.Current { [DebuggerHidden] get; } object IEnumerator.Current { [DebuggerHidden] get; } } </pre> <br /> 간단하게 IEnumerator만을 구현한 클래스로 바뀌는 것을 볼 수 있습니다.<br /> <br /> <hr style='width: 50%' /><br /> <br /> 참고로, foreach 구문은 IEnumerator/IEnumerable 인터페이스를 구현하지 않아도 되므로,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > 47. foreach 문을 사용하려면 IEnumerator/IEnumerable 인터페이스를 반드시 구현해야 할까? ; <a target='tab' href='http://www.sysnet.pe.kr/2/0/11876#tag47'>http://www.sysnet.pe.kr/2/0/11876#tag47</a> </pre> <br /> NameSet의 IEnumerable 상속은 (foreach에서만 사용한다면) 제거해도 무방합니다.<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
7311
(왼쪽의 숫자를 입력해야 합니다.)