當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C# Queue.Enqueue()用法及代碼示例


此方法用於將對象添加到隊列的末尾。這屬於System.Collections命名空間。該值可以為null,並且如果Count小於內部數組的容量,則此方法是O(1)操作。如果需要重新分配內部數組以容納新元素,則此方法將成為O(n)操作,其中n是Count。

用法:

public virtual void Enqueue (object obj);

在這裏,obj是添加到隊列中的對象。


例:

// C# code to illustarte the  
// Queue.Enqueue() 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("one"); 
  
        // Displaying the count of elements 
        // contained in the Queue 
        Console.Write("Total number of elements in the Queue are : "); 
  
        Console.WriteLine(myQueue.Count); 
  
        myQueue.Enqueue("two"); 
  
        // Displaying the count of elements 
        // contained in the Queue 
        Console.Write("Total number of elements in the Queue are : "); 
  
        Console.WriteLine(myQueue.Count); 
  
        myQueue.Enqueue("three"); 
  
        // Displaying the count of elements 
        // contained in the Queue 
        Console.Write("Total number of elements in the Queue are : "); 
  
        Console.WriteLine(myQueue.Count); 
  
        myQueue.Enqueue("four"); 
  
        // Displaying the count of elements 
        // contained in the Queue 
        Console.Write("Total number of elements in the Queue are : "); 
  
        Console.WriteLine(myQueue.Count); 
  
        myQueue.Enqueue("five"); 
  
        // Displaying the count of elements 
        // contained in the Queue 
        Console.Write("Total number of elements in the Queue are : "); 
  
        Console.WriteLine(myQueue.Count); 
  
        myQueue.Enqueue("six"); 
  
        // 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 : 1
Total number of elements in the Queue are : 2
Total number of elements in the Queue are : 3
Total number of elements in the Queue are : 4
Total number of elements in the Queue are : 5
Total number of elements in the Queue are : 6

參考:



相關用法


注:本文由純淨天空篩選整理自Kirti_Mangal大神的英文原創作品 Queue.Enqueue() Method in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。