此方法在不删除队列的情况下返回该对象。此方法类似于出队方法,但是Peek不会修改Queue,并且是O(1)操作。此方法位于System.Collections命名空间下。
句法:
public virtual object Peek ();
返回值:队列开始处的对象。
异常:如果Queue为空,则此方法将提供InvalidOperationException。
下面的程序说明了上面讨论的方法的使用:
范例1:
// C# code to illustrate the
// Queue.Peek Method
using System;
using System.Collections;
class GFG {
// Driver code
public static void Main()
{
// Creating a Queue
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 illustrate the
// Queue.Peek Method
using System;
using System.Collections;
class GFG {
// Driver code
public static void Main()
{
// Creating a Queue
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());
}
}
运行时错误:
Unhandled Exception:
System.InvalidOperationException: Queue empty.
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.queue.peek?view=netframework-4.7.2