此方法在不删除队列的情况下返回该对象。此方法类似于出队方法,但是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.
参考:
相关用法
- C# Dictionary.Add()用法及代码示例
- C# Math.Abs()函数用法及代码示例
- C# Stack.Contains()用法及代码示例
- C# Math.Exp()用法及代码示例
- C# Math.Abs()方法用法及代码示例
注:本文由纯净天空筛选整理自Kirti_Mangal大神的英文原创作品 Queue.Peek Method in C#。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。