當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C# Stack.GetEnumerator用法及代碼示例

此方法返回一個在堆棧中迭代的IEnumerator。它屬於System.Collections命名空間。

用法:

public virtual System.Collections.IEnumerator GetEnumerator ();

以下示例程序旨在說明上述方法的使用:


示例1:

// C# program to illustrate the 
// Stack.GetEnumerator Method 
using System; 
using System.Collections; 
  
class GFG { 
  
    // Driver code 
    public static void Main() 
    { 
  
        // Creating a Stack 
        Stack myStack = new Stack(); 
  
        // Inserting the elements into the Stack 
        myStack.Push("Geeks"); 
        myStack.Push("Geeks Classes"); 
        myStack.Push("Noida"); 
        myStack.Push("Data Structures"); 
        myStack.Push("GeeksforGeeks"); 
  
        // To get an Enumerator 
        // for the Stack 
        IEnumerator enumerator = myStack.GetEnumerator(); 
  
        // If MoveNext passes the end of the 
        // collection, the enumerator is positioned 
        // after the last element in the Stack 
        // and MoveNext returns false. 
        while (enumerator.MoveNext()) { 
  
            Console.WriteLine(enumerator.Current); 
        } 
    } 
}
輸出:
GeeksforGeeks
Data Structures
Noida
Geeks Classes
Geeks

示例2:

// C# code to illustrate the 
// Stack.GetEnumerator Method 
using System; 
using System.Collections; 
  
class GFG { 
  
    // Driver code 
    public static void Main() 
    { 
  
        // Creating a Stack 
        Stack myStack = new Stack(); 
  
        // Inserting the elements into the Stack 
        myStack.Push(2); 
        myStack.Push(3); 
        myStack.Push(4); 
        myStack.Push(5); 
        myStack.Push(6); 
  
        // To get an Enumerator 
        // for the Stack 
        IEnumerator enumerator = myStack.GetEnumerator(); 
  
        // If MoveNext passes the end of the 
        // collection, the enumerator is positioned 
        // after the last element in the Stack 
        // and MoveNext returns false. 
        while (enumerator.MoveNext()) { 
  
            Console.WriteLine(enumerator.Current); 
        } 
    } 
}
輸出:
6
5
4
3
2

注意:

  • C#語言的foreach語句隱藏了枚舉器的複雜性。因此,建議使用foreach,而不是直接操作枚舉器。
  • 枚舉數可用於讀取集合中的數據,但不能用於修改基礎集合。
  • 當前返回相同的對象,直到調用MoveNext或Reset。 MoveNext將Current設置為下一個元素。
  • 隻要集合保持不變,枚舉數將保持有效。如果對集合進行了更改(例如添加,修改或刪除元素),則枚舉數將無法恢複,並且其行為是不確定的。
  • 此方法是O(1)操作。

參考:



相關用法


注:本文由純淨天空篩選整理自Kirti_Mangal大神的英文原創作品 Stack.GetEnumerator Method in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。