📜  在C#中的队列开始处获取对象

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

Dequeue()方法用于返回队列开始处的对象。此方法类似于Peek()方法。 Dequeue和Peek方法之间的唯一区别是Peek()方法不会修改Queue,但会修改Dequeue。此方法是O(1)操作,位于System.Collections.Generic命名空间下。

句法:

public T Dequeue ();

返回值:返回从队列开头删除的对象。

异常:该方法在调用空队列时引发InvalidOperationException ,因此,在调用Dequeue()方法之前,请始终检查队列的总数是否大于零。

下面的程序说明了上述方法的用法:

// C# Program to illustrate the use
// of Queue.Dequeue Method
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
  
        // creating a queue of integers
        Queue queue = new Queue();
        queue.Enqueue(3);
        queue.Enqueue(2);
        queue.Enqueue(1);
        queue.Enqueue(4);
  
        Console.WriteLine("Number of elements in the Queue: {0}",
                                                   queue.Count);
  
        // Retrieveing top element of queue
        Console.WriteLine("Top element of queue is:");
        Console.WriteLine(queue.Dequeue());
  
        // printing the no of queue element
        // after dequeue operation
        Console.WriteLine("Number of elements in the Queue: {0}",
                                                   queue.Count);
    }
}
输出:
Number of elements in the Queue: 4
Top element of queue is:
3
Number of elements in the Queue: 3

范例2:

// C# Program to illustrate the use
// of Queue.Dequeue Method
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        Queue queue = new Queue();
  
        // Adding elements in Queue
        queue.Enqueue(2);
        queue.Enqueue(5);
  
        Console.WriteLine("Number of elements in the Queue: {0}",
                                                    queue.Count);
  
        // Retrieveing top element of queue
        Console.WriteLine("Top element of queue is:");
        Console.WriteLine(queue.Dequeue());
  
        // printing the no. of queue element
        // after dequeue operation
        Console.WriteLine("Number of elements in the Queue: {0}",
                                                   queue.Count);
    }
}
输出:
Number of elements in the Queue: 2
Top element of queue is:
2
Number of elements in the Queue: 1

参考:

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