Microsoft MVP성태의 닷넷 이야기
yield return의 리턴 타입 질문 드립니다. [링크 복사], [링크+제목 복사]
조회: 7108
글쓴 사람
rysoo
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

안녕하세요 yield 키워드 공부 중에 이해가 잘 안 되는 부분이 있어 질문 드립니다.


yield return을 사용하는 함수의 리턴 타입이 IEnumerable일 때가 있고, IEnumerator일 때가 있던데 두가지 차이가 정확히 이해가 잘 안 됩니다. ㅠㅠ


단순히 foreach 구문의 in 뒤에 나오는 IEnumerable 객체를 클래스의 함수로 부르고 싶을 때, yield return이 사용되는 IEnumerbale 반환 함수를 만들면 되고,


클래스 자체에 IEnumerable을 상속 받아 GetEnumerator 함수를 구현하고자 할 때, IEnumerator를 반환하는 GetEnumerator 함수를 만들면 되는걸까요?


두가지 구현 방식의 차이점이 어떤 건지 궁금합니다.


[연관 글]






[최초 등록일: ]
[최종 수정일: 5/8/2019]


비밀번호

댓글 작성자
 



2019-05-08 12시54분
코드와 함께 질문해 주세요.
정성태
2019-05-08 03시10분
[rysoo] using System;
using System.Collections;
using System.Collections.Generic;

public class NameSet
{
    private List<string> names = new List<string>();

    public NameSet(params string[] values)
    {
        foreach (var e in values)
            this.names.Add(e);
    }

    public IEnumerable NameList()
    {
        int currentIndex = 0;

        while (currentIndex < names.Count)
        {
            yield return names[currentIndex];
            currentIndex++;
        }
    }
}

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var names = new NameSet("abc", "def", "ghi");

            foreach (var e in names.NameList())
                Console.WriteLine(e);
                
        }
    }
}


위 코드를 아래와 같이 바꿔도 동일한 결과가 나오는데 두 가지 차이가 궁금합니다.


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);
    }

    public IEnumerator GetEnumerator()
    {
        int currentIndex = 0;

        while (currentIndex < names.Count)
        {
            yield return names[currentIndex];
            currentIndex++;
        }
    }
}

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var names = new NameSet("abc", "def", "ghi");

            foreach (var e in names)
                Console.WriteLine(e);
                
        }
    }
}

yield도 결국 간편 표기법이라고 하셨는데, 컴파일러가 위 두 코드를 동일하게 치환해서 처리를 하는 걸까요?
[guest]
2019-05-08 07시35분
다음의 글을 참조하시고,

C# - yield 문을 사용할 수 있는 메서드의 조건
; http://www.sysnet.pe.kr/2/0/11887

혹시 설명이 덜 되었다면 그 부분을 다시 질문해주세요. 그에 따라 부가 설명을 추가하겠습니다.
정성태
2019-05-08 11시45분
[rysoo] 많은 도움 되었습니다~~. 답변 감사합니다.
[guest]

[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
5922He...10/27/20231481C++의 double pointer를 C#에서 구현하는 방법이 잘 안됩니다. [3]
5921한예지10/3/20232081마샬링 정의 및 목적이 궁금합니다. [5]
5920한예지10/3/20231663C#과 WIN32 API 관계 질문드립니다. [4]
5919이건우9/27/20231447WinForm의 로딩속도 관련 질문입니다 [2]
5917한예지9/14/20231574동기화 도구 질문 있습니다. [4]
5916한예지9/3/20231687Thread.Sleep(500), await Task.Delay(500), Task.Delay(500) 차이점이 궁금합니다. [2]
5915한예지8/30/20231610비동기 코드를 for 문 안에 작성한 경우 제어 변수가 올바르게 동작하지 않는 이유가 궁금합니다. [3]
5914한상욱8/11/20231611.net wpf에서 skiasharp 의 skelement 를 canvas로 사용 하고 있습니다. [1]
5913김태우8/10/20231803지역변수로 이해하는 메서드매개변수 게시글 댓글 [3]
5912guest4/25/20233332[참고 - 초보용] Sqlite 디비는 double이 없고 Real이 대신합니다 [3]
5911guest4/24/20232222Form1.cs와 외부 class.cs와 통신 (static async method포함) [4]파일 다운로드1
5910guest4/24/20231968Async 메서드와 try~catch [1]
5909guest4/22/20232173Visual Studio 구매 시(1인 개발자) [4]
5908guest4/22/20232031텅빈 원그리기 [5]
5907민성4/21/20231863안녕하세요 서버 백업 문제에 대해서 [2]
5906guest4/21/20231930Dispatcher 서비스 구현 질문 [1]
5905guest4/20/20232034tabControl의 tabPage가 여러 개일 때 순서를 바꾸기가 까다롭네요 [5]
5904guest4/18/20232131[신규자료첨부] DLL 'SQLite.Interop.dll'을 찾을 수 없습니다 [4]파일 다운로드1
5903guest4/18/20231787fileSystemWatcher 이벤트 관련 질문입니다 [2]
5902guest4/17/20232247c#으로 USB 관련 질문 [2]
5901guest4/17/20232039내솔루션 판매 시 1.0.0.0 폴더와 Sqlite 배포 [5]
5900guest4/17/20232881DLL 'SQLite.Interop.dll'을 찾을 수 없습니다 [2]파일 다운로드1
5899guest4/17/20232169Dictionary와 Linq [4]
5898차가워4/17/20231953CNTK 교육 문의 [1]
5897guest4/17/20232065Socket스레드와 UI thread [4]
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...