此方法返回一个在堆栈中迭代的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)操作。
 
参考:
相关用法
- C# Dictionary.Add()用法及代码示例
 - C# Math.Abs()方法用法及代码示例
 - C# Math.Abs()函数用法及代码示例
 - C# Math.Exp()用法及代码示例
 - C# Queue.Contains()用法及代码示例
 - C# Stack.Pop()用法及代码示例
 
注:本文由纯净天空筛选整理自Kirti_Mangal大神的英文原创作品 Stack.GetEnumerator Method in C#。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
