📜  C#中的Queue.Clear方法

📅  最后修改于: 2021-05-29 22:05:20             🧑  作者: Mango

此方法用于从队列中删除对象。此方法是O(n)运算,其中n是元素总数。而且此方法位于System.Collections命名空间下。

句法:

public void Clear ();

下面给出了一些示例,以更好地理解实现:

范例1:

// C# code to illustrate the
// Queue.Clear Method
using System;
using System.Collections;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a Queue
        Queue q = new Queue();
  
        // Inserting the elements into the Queue
        q.Enqueue(1);
        q.Enqueue(2);
        q.Enqueue(2);
        q.Enqueue(4);
  
        // Displaying the count of elements
        // contained in the Queue before
        // removing all the elements
        Console.Write("Total number of elements "+
                           "in the Queue are : ");
  
        Console.WriteLine(q.Count);
  
        // Removing all elements from Queue
        q.Clear();
  
        // Displaying the count of elements
        // contained in the Queue after
        // removing all the elements
        Console.Write("Total number of elements"+
                         " in the Queue are : ");
  
        Console.WriteLine(q.Count);
    }
}
输出:
Total number of elements in the Queue are : 4
Total number of elements in the Queue are : 0

范例2:

// C# code to illustrate the
// Queue.Clear Method
using System;
using System.Collections;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a Queue
        Queue q = new Queue();
   
        // Inserting the elements into the Queue
        q.Enqueue("C");
        q.Enqueue("C++");
        q.Enqueue("Java");
        q.Enqueue("PHP");
        q.Enqueue("HTML");
        q.Enqueue("Python");
  
        // Displaying the count of elements
        // contained in the Queue before
        // removing all the elements
        Console.Write("Total number of elements "+
                           "in the Queue are : ");
  
        Console.WriteLine(q.Count);
  
        // Removing all elements from Queue
        q.Clear();
  
        // Displaying the count of elements
        // contained in the Queue after
        // removing all the elements
        Console.Write("Total number of elements "+
                           "in the Queue are : ");
  
        Console.WriteLine(q.Count);
    }
}
输出:
Total number of elements in the Queue are : 6
Total number of elements in the Queue are : 0

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.queue.clear?view=netframework-4.7.2