Phương thức Stack.GetEnumerator() trong C# được sử dụng để trả về một IEnumerator cho Stack.
Cú pháp
public virtual System.Collections.IEnumerator GetEnumerator ();
Ví dụ
Dưới đây là một ví dụ minh họa:
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("Các phần tử của Stack1...");
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("Các phần tử của Stack2...");
while (demoEnum.MoveNext()) {
Console.WriteLine(demoEnum.Current);
}
Console.WriteLine("\nHai stack có bằng nhau? = " + stack1.Equals(stack2));
}
}
Kết quả
Chương trình sẽ cho ra kết quả sau:
Các phần tử của Stack1... 1000 750 500 300 150 Các phần tử của Stack2... 900 850 500 400 350 Hai stack có bằng nhau? = False
Ví dụ khác
Một ví dụ khác với các chuỗi:
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("Các phần tử của Stack...");
foreach(string val in stack){
Console.WriteLine(val);
}
Console.WriteLine("Số lượng phần tử = " + stack.Count);
Console.WriteLine("Phần tử 'Speakers' có trong stack? = " + stack.Contains("Speakers"));
stack.Push("Headphone");
stack.Push("Keyboard");
stack.Push("Earphone");
Console.WriteLine("\nCác phần tử của Stack...đã cập nhật");
foreach(string val in stack){
Console.WriteLine(val);
}
Console.WriteLine("Số lượng phần tử (đã cập nhật) = " + stack.Count);
Console.WriteLine("\nPhần tử 'Alienware' có trong stack? = " + stack.Contains("Alienware"));
Stack stack2 = (Stack)stack.Clone();
Console.WriteLine("\nCác phần tử của Stack...đã sao chép");
IEnumerator demoEnum = stack2.GetEnumerator();
while (demoEnum.MoveNext()) {
Console.WriteLine(demoEnum.Current);
}
Console.WriteLine("Số lượng phần tử (đã cập nhật) = " + stack.Count);
}
}
Kết quả
Các phần tử của Stack... Notebook Laptop XPS Monitors Projectors Alienware Inspiron Số lượng phần tử = 7 Phần tử 'Speakers' có trong stack? = False Các phần tử của Stack...đã cập nhật Earphone Keyboard Headphone Notebook Laptop XPS Monitors Projectors Alienware Inspiron Số lượng phần tử (đã cập nhật) = 10 Phần tử 'Alienware' có trong stack? = True Các phần tử của Stack...đã sao chép Earphone Keyboard Headphone Notebook Laptop XPS Monitors Projectors Alienware Inspiron Số lượng phần tử (đã cập nhật) = 10