C#中的Queue.Peek()方法用于在不删除队列的情况下返回队列的开头的对象。
语法如下-
public virtual object Peek ();
现在让我们看一个例子-
using System; using System.Collections; public class Demo { public static void Main() { Queue queue = new Queue(); queue.Enqueue("AB"); queue.Enqueue("BC"); queue.Enqueue("CD"); queue.Enqueue("DE"); queue.Enqueue("EF"); queue.Enqueue("FG"); queue.Enqueue("GH"); queue.Enqueue("HI"); Console.WriteLine("Queue..."); IEnumerator demoEnum = queue.GetEnumerator(); while (demoEnum.MoveNext()) { Console.WriteLine(demoEnum.Current); } Console.WriteLine("Queue element at the beginning = "+queue.Peek()); Console.WriteLine("Is Queue synchronized? = "+queue.IsSynchronized); Queue queue2 = Queue.Synchronized(queue); Console.WriteLine("Is Queue synchronized now? = "+queue2.IsSynchronized); } }
输出结果
这将产生以下输出-
Queue... AB BC CD DE EF FG GH HI Queue element at the beginning = AB Is Queue synchronized? = False Is Queue synchronized now? = True
现在让我们来看另一个示例-
using System; using System.Collections.Generic; public class Demo { public static void Main() { Queue<string> queue = new Queue<string>(); queue.Enqueue("Gary"); queue.Enqueue("Jack"); queue.Enqueue("Ryan"); queue.Enqueue("Kevin"); queue.Enqueue("Mark"); queue.Enqueue("Jack"); queue.Enqueue("Ryan"); queue.Enqueue("Kevin"); Console.Write("Count of elements = "); Console.WriteLine(queue.Count); Console.WriteLine("Queue element at the beginning = "+queue.Peek()); Console.WriteLine("Does the queue has element Jack? = "+queue.Contains("Jack")); queue.Clear(); Console.Write("Count of elements (updated) = "); Console.WriteLine(queue.Count); } }
输出结果
这将产生以下输出-
Count of elements = 8 Queue element at the beginning = Gary Does the queue has element Jack? = True Count of elements (updated) = 0