当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C# Queue.Dequeue用法及代码示例


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

用法:

public virtual object Dequeue ();

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


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

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

// C# Program to illustrate the use  
// of Queue.Dequeue Method 
using System; 
using System.Collections; 
  
class GFG { 
  
    // Main Method 
    public static void Main() 
    { 
        Queue queue = new Queue(); 
        queue.Enqueue(3); 
        queue.Enqueue(2); 
        queue.Enqueue(1); 
        queue.Enqueue("Four"); 
  
        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
// C# Program to illustrate the use  
// of Queue.Dequeue Method 
using System; 
using System.Collections; 
  
class GFG { 
  
    // Main Method 
    public static void Main() 
    { 
        Queue queue = new Queue(); 
  
        // Adding elements in Queue 
        queue.Enqueue(2); 
        queue.Enqueue("Four"); 
  
        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

参考:



相关用法


注:本文由纯净天空筛选整理自Twinkl Bajaj大神的英文原创作品 Queue.Dequeue Method in C#。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。