📜  C#中的Queue.GetEnumerator方法

📅  最后修改于: 2021-05-29 17:01:14             🧑  作者: Mango

此方法返回一个遍历Queue的枚举数。它位于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之前,Current返回相同的对象。 MoveNextCurrent设置为下一个元素。
  • 只要集合保持不变,枚举数将保持有效。如果对集合进行了更改(例如添加,修改或删除元素),则枚举数将无法恢复,并且其行为是不确定的。
  • 此方法是O(1)操作。

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.queue.getenumerator?view=netframework-4.7.2