C#中的Queue.Clear()方法用于从Queue中清除所有对象。
语法如下-
public virtual void Clear ();
现在让我们看一个例子-
using System; using System.Collections.Generic; public class Demo { public static void Main() { Queue<int> queue = new Queue<int>(); queue.Enqueue(100); queue.Enqueue(200); queue.Enqueue(300); queue.Enqueue(400); queue.Enqueue(500); queue.Enqueue(600); queue.Enqueue(700); queue.Enqueue(800); queue.Enqueue(900); queue.Enqueue(1000); Console.WriteLine("Queue..."); foreach(int i in queue) { Console.WriteLine(i); } Console.WriteLine("Count of elements in the Queue = "+queue.Count); queue.Clear(); Console.WriteLine("Count of elements in the Queue [Updated] = "+queue.Count); } }
输出结果
这将产生以下输出-
Queue... 100 200 300 400 500 600 700 800 900 1000 Count of elements in the Queue = 10 Count of elements in the Queue [Updated] = 0
现在让我们来看另一个例子-
using System; using System.Collections.Generic; public class Demo { public static void Main() { Queue<int> queue = new Queue<int>(); queue.Enqueue(100); queue.Enqueue(200); queue.Enqueue(300); Console.WriteLine("Queue..."); foreach(int i in queue) { Console.WriteLine(i); } Console.WriteLine("Count of elements in the Queue = "+queue.Count); queue.Enqueue(800); queue.Enqueue(900); queue.Enqueue(1000); Console.WriteLine("Count of elements in the Queue [Updated] = "+queue.Count); queue.Clear(); Console.WriteLine("Count of elements in the Queue [Updated] = "+queue.Count); } }
输出结果
这将产生以下输出-
Queue... 100 200 300 Count of elements in the Queue = 3 Count of elements in the Queue [Updated] = 6 Count of elements in the Queue [Updated] = 0