Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C# Stack.GetEnumerator() 메서드 완벽 정리 – 구문, 예제, 실행 결과까지

C#의 Stack.GetEnumerator() 메서드는 스택(Stack) 컬렉션을 순회할 수 있는 IEnumerator 객체를 반환합니다. 이 메서드를 활용하면 foreach 문 없이도 MoveNext() 메서드와 Current 속성을 통해 스택의 각 요소에 하나씩 접근할 수 있습니다.

구문

메서드의 구문은 다음과 같습니다.

public virtual System.Collections.IEnumerator GetEnumerator();

주요 특징

  • 스택은 LIFO(Last-In-First-Out, 후입선출) 구조이므로, 열거 시 가장 마지막에 Push된 요소부터 먼저 반환됩니다.
  • 반환되는 IEnumerator는 읽기 전용이며, 컬렉션의 데이터를 수정하는 용도로는 사용할 수 없습니다.
  • C#의 foreach 문은 내부적으로 GetEnumerator() 메서드를 호출하여 동작합니다.

예제 1: 정수형 스택 순회하기

다음 예제에서는 두 개의 정수형 스택을 생성한 뒤, GetEnumerator() 메서드를 사용해 요소를 순회하는 방법을 살펴봅니다.

using System;
using System.Collections;

public class Demo {
    public static void Main() {
        Stack stack1 = new Stack();
        stack1.Push(150);
        stack1.Push(300);
        stack1.Push(500);
        stack1.Push(750);
        stack1.Push(1000);
        
        Console.WriteLine("Stack1 elements...");
        foreach(int val in stack1) {
            Console.WriteLine(val);
        }
        
        Stack stack2 = new Stack();
        stack2.Push(350);
        stack2.Push(400);
        stack2.Push(500);
        stack2.Push(850);
        stack2.Push(900);
        
        IEnumerator demoEnum = stack2.GetEnumerator();
        Console.WriteLine("Stack2 elements...");
        while (demoEnum.MoveNext()) {
            Console.WriteLine(demoEnum.Current);
        }
        
        Console.WriteLine("\nAre both the stacks equal? = " + stack1.Equals(stack2));
    }
}

실행 결과

위 코드를 실행하면 다음과 같은 출력이 생성됩니다.

Stack1 elements...
1000
750
500
300
150
Stack2 elements...
900
850
500
400
350
Are both the stacks equal? = False

예제 2: 문자열 스택과 Clone() 함께 활용하기

두 번째 예제에서는 문자열 스택에 요소를 추가·확인한 후, Clone() 메서드로 복제한 스택을 GetEnumerator()로 순회하는 과정을 보여줍니다.

using System;
using System.Collections;

public class Demo {
    public static void Main() {
        Stack stack = new Stack();
        stack.Push("Inspiron");
        stack.Push("Alienware");
        stack.Push("Projectors");
        stack.Push("Monitors");
        stack.Push("XPS");
        stack.Push("Laptop");
        stack.Push("Notebook");
        
        Console.WriteLine("Stack elements...");
        foreach(string val in stack) {
            Console.WriteLine(val);
        }
        
        Console.WriteLine("Count of elements = " + stack.Count);
        Console.WriteLine("Element Speakers is the stack? = " + stack.Contains("Speakers"));
        
        stack.Push("Headphone");
        stack.Push("Keyboard");
        stack.Push("Earphone");
        
        Console.WriteLine("\nStack elements...updated");
        foreach(string val in stack) {
            Console.WriteLine(val);
        }
        
        Console.WriteLine("Count of elements (updated) = " + stack.Count);
        Console.WriteLine("\nElement Alienware is the stack? = " + stack.Contains("Alienware"));
        
        Stack stack2 = (Stack)stack.Clone();
        Console.WriteLine("\nStack elements...cloned");
        
        IEnumerator demoEnum = stack2.GetEnumerator();
        while (demoEnum.MoveNext()) {
            Console.WriteLine(demoEnum.Current);
        }
        
        Console.WriteLine("Count of elements (updated) = " + stack.Count);
    }
}

실행 결과

위 코드를 실행하면 다음과 같은 출력이 생성됩니다.

Stack elements...
Notebook
Laptop
XPS
Monitors
Projectors
Alienware
Inspiron
Count of elements = 7
Element Speakers is the stack? = False
Stack elements...updated
Earphone
Keyboard
Headphone
Notebook
Laptop
XPS
Monitors
Projectors
Alienware
Inspiron
Count of elements (updated) = 10
Element Alienware is the stack? = True
Stack elements...cloned
Earphone
Keyboard
Headphone
Notebook
Laptop
XPS
Monitors
Projectors
Alienware
Inspiron
Count of elements (updated) = 10

정리

Stack.GetEnumerator() 메서드는 스택의 요소를 IEnumerator 형태로 순회할 수 있게 해주는 기본적인 열거 도구입니다. foreach 문으로도 동일한 결과를 얻을 수 있지만, MoveNext()와 Current를 직접 제어해야 하는 상황이나 Clone()으로 복제한 컬렉션을 순회할 때 유용하게 활용할 수 있습니다.