📜  C#中的Queue.Enqueue()方法

📅  最后修改于: 2021-05-30 01:47:50             🧑  作者: Mango

此方法用于将对象添加到队列的末尾。它位于System.Collections命名空间下。该值可以为null,并且如果Count小于内部数组的容量,则此方法是O(1)操作。如果需要重新分配内部数组以容纳新元素,则此方法将成为O(n)操作,其中n为Count。
句法 :

public virtual void Enqueue (object obj);

在这里, obj是添加到队列中的对象。
例子:

CSHARP
// C# code to illustrate 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

参考:

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