📜  C#|在队列开始处获取对象–窥视操作

📅  最后修改于: 2021-05-29 23:48:59             🧑  作者: Mango

队列代表对象的先进先出集合。当您需要对项目进行先进先出的访问时,可以使用它。当您在列表中添加一个项目时,它称为enqueue ,而当您删除一个项目时,它称为deque队列。偷看方法用于在队列开始处获取对象而不删除它。

特性:

  • Enqueue将元素添加到队列的末尾。
  • 出队从队列开始处删除最旧的元素。
  • Peek返回位于队列开始处的最旧元素,但不会将其从队列中删除。
  • 队列的容量是队列可以容纳的元素数。
  • 随着元素添加到队列中,通过重新分配内部数组,容量会根据需要自动增加。
  • 队列接受null作为引用类型的有效值,并允许重复的元素。

句法 :

object Peek(); 

返回值: Peek()方法始终返回队列集合中的第一项,而不会将其从队列中删除。在空队列集合上调用Peek()Dequeue()方法将引发运行时异常“ InvalidOperationException”。

下面给出了一些示例,以更好地理解实现:

范例1:

// C# code to Get object at
// the beginning of the Queue
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a Queue of strings
        Queue myQueue = new Queue();
  
        // Inserting the elements into the Queue
        myQueue.Enqueue("1st Element");
        myQueue.Enqueue("2nd Element");
        myQueue.Enqueue("3rd Element");
        myQueue.Enqueue("4th Element");
        myQueue.Enqueue("5th Element");
        myQueue.Enqueue("6th Element");
  
        // Displaying the count of elements
        // contained in the Queue
        Console.Write("Total number of elements in the Queue are : ");
  
        Console.WriteLine(myQueue.Count);
  
        // Displaying the beginning element of Queue
        // without removing it from the Queue
        Console.WriteLine("Element at the beginning is : " + myQueue.Peek());
  
        // Displaying the beginning element of Queue
        // without removing it from the Queue
        Console.WriteLine("Element at the beginning is : " + myQueue.Peek());
  
        // Displaying the count of elements
        // contained in the Queue
        Console.Write("Total number of elements in the Queue are : ");
  
        Console.WriteLine(myQueue.Count);
    }
}
输出:
Total number of elements in the Queue are : 6
Element at the beginning is : 1st Element
Element at the beginning is : 1st Element
Total number of elements in the Queue are : 6

范例2:

// C# code to Get object at
// the beginning of the Queue
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a Queue of Integers
        Queue myQueue = new Queue();
  
        // Displaying the beginning element of Queue
        // without removing it from the Queue
        // Calling Peek() method on empty Queue
        // will throw InvalidOperationException.
        Console.WriteLine("Element at the beginning is : " + myQueue.Peek());
    }
}

运行时错误:

参考:

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