此方法在不刪除隊列的情況下返回該對象。此方法類似於出隊方法,但是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#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。