본문 바로가기
C#/C# 강의 정리

C# yield문

by 민트코코넛 2020. 12. 29.
728x90
반응형

§ Yeild 문 §

◈ 호출자에게 컬렉션 데이터를 하나씩 리턴할 때 사용한다.

- Collection : ArrayList, Stack, Queue, Hashtable... (Collection 정리 참조)

class MyClass
{
    static void Main(string[] args)
    {
        //int[] scores = new int[] {1, 2, 3 };
        int[] arr = GetScores();
        //foreach (var item in arr)
        foreach ( var item in GetScores())
        {
            Console.WriteLine(item);
        }
    }
    static int[] GetScores( )
    {
        int[] scores = new int[] { 1, 2, 3 };
        return scores;
    }
}

§ Yield return 문 - basic §

- 인터페이스의 값을 하나씩 빼서 외부로 되돌려준다.

 

◈ 사용방법 1 : using으로 System.Collectons.Generic;을 선언해준다.

- IEnumerable<T> 인터페이스와 Yield문이 하나 이상 사용될 때, 해당 라이브러리를 참조하겠다는 의미로 시작 코드에 using으로 선언해주어 간편하게 사용하도록 한다.

using System.Collections.Generic;
class MyClass
{
    static void Main(string[] args)
    {
            
        //int[] scores = new int[] {1, 2, 3 };
        //int[] arr = GetScores();
        //foreach (var item in arr)
        foreach (var item in GetScores())
        {
            Console.WriteLine(item);
        }
    }
    static int[] GetScore()
        // foreach 실행시, 전체 리턴
    {
        int[] scores = new int[] { 1, 2, 3 };
        return scores;
    }

    static IEnumerable<int> GetScores()
    // yield 문과 짝을 이루는 메서드
    // foreach 실행시, 값을 하나씩 리턴
    {
        int[] scores = new int[] { 1, 2, 3 };
        yield return scores[0];
        yield return scores[1];
        yield return scores[2];
    }
}

 사용방법 2 : using으로 선언하지 않은 경우, 해당 인터페이스의 앞부분에 System.Collectons.Generic. 을 추가.

class MyClass
{
    static void Main(string[] args)
    {
        foreach (var item in GetScores())
        {
            Console.WriteLine(item);
        }
    }
    static int[] GetScore()
        // foreach 실행시, 전체 리턴
    {
        int[] scores = new int[] { 1, 2, 3 };
        return scores;
    }

    static System.Collections.Generic.IEnumerable<int> GetScores()
    // yield 문과 짝을 이루는 메서드
    // foreach 실행시, 값을 하나씩 리턴
    {
        int[] scores = new int[] { 1, 2, 3 };
        yield return scores[0];
        yield return scores[1];
        yield return scores[2];
    }
}

§ Yield return 문 - for §

- 일반적인 yield return문은 값을 일일히 하나씩 빼서 돌려줘야 하는 불편함을 for반복문을 통해서 index를 하나씩 증가시키면서 자동적으로 처리하도록 구성한 형태.

 배열 내부의 값을 for문을 통해서 하나씩 빼내고, 이를 yield로 return하는 방식.

class MyClass
{
    static void Main(string[] args)
    {

        //int[] scores = new int[] {1, 2, 3 };
        //int[] arr = GetScores();
        //foreach (var item in arr)
        foreach (var item in GetScores())
        {
            Console.WriteLine(item);
        }
    }
    static int[] GetScore()
    // foreach 실행시, 전체 리턴
    {
        int[] scores = new int[] { 1, 2, 3 };
        return scores;
    }

    static System.Collections.Generic.IEnumerable<int> GetScores()
    // yield 문과 짝을 이루는 메서드
    // foreach 실행시, 값을 하나씩 리턴
    {
        int[] scores = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        for (int i = 0; i < scores.Length; i++)
        {
            yield return scores[i];
        }
    }
}

§ Yield break 문 §

- yield문을 진행하는 중간에 빠져나가려고 할 때 사용한다.

class MyClass
{
    static void Main(string[] args)
    {

        foreach (var item in GetScores())
        {
            Console.WriteLine(item);
        }
    }
    static int[] GetScore()
    // foreach 실행시, 전체 리턴
    {
        int[] scores = new int[] { 1, 2, 3 };
        return scores;
    }

    static System.Collections.Generic.IEnumerable<int> GetScores()
    // yield 문과 짝을 이루는 메서드
    // foreach 실행시, 값을 하나씩 리턴
    {
        int[] scores = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        for (int i = 0; i < scores.Length; i++)
        {
            if (scores[i] == 4) 
            {
                yield break;
            }

            yield return scores[i];
        }
    }
}

§ Yield 예제 §

- 인터페이스에서 배열 내부의 값을 모두 합산한 후, yield를 통해서 리턴하여 출력하기.

class MyClass
{
    static void Main(string[] args)
    {

        foreach (var item in GetScores())
        {
            Console.WriteLine(item);
        }
    }
    static int[] GetScore()
    // foreach 실행시, 전체 리턴
    {
        int[] scores = new int[] { 1, 2, 3 };
        return scores;
    }

    static System.Collections.Generic.IEnumerable<int> GetScores()
    // yield 문과 짝을 이루는 메서드
    // foreach 실행시, 값을 하나씩 리턴
    {
        int[] scores = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        int total = 0;
        for (int i = 0; i < scores.Length; i++)
        {
            total += scores[i];

            yield return total;
        }
    }
}

 

728x90

'C# > C# 강의 정리' 카테고리의 다른 글

C# 열거형 (Enum)  (0) 2020.12.29
C# 매개 변수 ref, out, method overloading  (0) 2020.12.27
C# 제어문  (0) 2020.12.27
C# 배열  (0) 2020.12.27
C# 함수  (0) 2020.12.27