此方法返回一个遍历队列的枚举数。它位于System.Collections命名空间下。
用法:
public virtual System.Collections.IEnumerator GetEnumerator ();
以下示例程序旨在说明上述方法的使用:
示例1:
// C# code to illustrate the  
// Queue.GetEnumerator Method  
using System; 
using System.Collections; 
  
class GFG { 
  
    // Driver code 
    public static void Main() 
    { 
  
        // Creating an Queue 
        Queue myq = new Queue(); 
  
        // Adding elements to Queue 
        myq.Enqueue("A"); 
        myq.Enqueue("B"); 
        myq.Enqueue("C"); 
        myq.Enqueue("D"); 
        myq.Enqueue("E"); 
        myq.Enqueue("F"); 
  
        // To get an Enumerator 
        // for the Queue 
        IEnumerator enumerator = myq.GetEnumerator(); 
  
        // If MoveNext passes the end of the 
        // collection, the enumerator is positioned 
        // after the last element in the Queue 
        // and MoveNext returns false. 
        while (enumerator.MoveNext())  
        { 
  
            Console.WriteLine(enumerator.Current); 
        } 
    } 
}
输出:
A B C D E F
示例2:
// C# code to illustrate the  
// Queue.GetEnumerator Method  
using System; 
using System.Collections; 
  
class GFG { 
  
    // Driver code 
    public static void Main() 
    { 
  
        // Creating an Queue 
        Queue myq = new Queue(); 
  
        // Adding elements to Queue 
        myq.Enqueue(78); 
        myq.Enqueue(84); 
        myq.Enqueue(44); 
        myq.Enqueue(77); 
        myq.Enqueue(99); 
  
        // To get an Enumerator 
        // for the Queue 
        IEnumerator enumerator = myq.GetEnumerator(); 
  
        // If MoveNext passes the end of the 
        // collection, the enumerator is positioned 
        // after the last element in the Queue 
        // and MoveNext returns false. 
        while (enumerator.MoveNext()) { 
  
            Console.WriteLine(enumerator.Current); 
        } 
    } 
}
输出:
78 84 44 77 99
注意:
- 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大神的英文原创作品 Queue.GetEnumerator Method in C#。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
