📜  如何在C#中创建队列

📅  最后修改于: 2021-05-29 23:44:30             🧑  作者: Mango

Queue()构造函数用于初始化Queue类的新实例,该实例将为空,并将具有默认的初始容量,并使用默认的增长因子。队列代表对象的先进先出集合。当您需要对项目进行先进先出的访问时,可以使用它。当您在列表中添加项目时,它称为入队,而当您删除项目时,它称为出队。此类位于System.Collections命名空间下,并实现ICollection,IEnumerable和ICloneable接口。

句法:

public Queue ();

重要事项:

  • 队列的容量表示队列可以容纳的元素数。随着元素的添加,它将通过重新分配自动增加。
  • TrimToSize方法用于减少队列的容量。
  • 如果需要更大的容量,则将当前容量乘以一个数字,该数字称为增长因子
  • 此构造函数是O(1)操作。

范例1:

// C# Program to illustrate how
// to create a Queue
using System;
using System.Collections;
  
class Geeks {
  
    // Main Method
    public static void Main(String[] args)
    {
  
        // qt is the Queue object
        // Queue() is the constructor
        // used to initializes a new 
        // instance of the Queue class
        Queue qt = new Queue();
  
        // Count property is used to get the
        // number of elements in Queue
        // It will give 0 as no elements 
        // are present currently
        Console.WriteLine(qt.Count);
    }
}
输出:
0

范例2:

// C# Program to illustrate how
// to create a Queue
using System;
using System.Collections;
  
class Geeks {
  
    // Main Method
    public static void Main(String[] args)
    {
  
        // qt is the Queue object
        // Queue() is the constructor
        // used to initializes a new 
        // instance of the Queue class
        Queue qt = new Queue();
  
        Console.Write("Before Enqueue Method: ");
          
        // Count property is used to get the
        // number of elements in Queue
        // It will give 0 as no elements 
        // are present currently
        Console.WriteLine(qt.Count);
  
        // Inserting the elements
        // into the Queue
        qt.Enqueue("This");
        qt.Enqueue("is");
        qt.Enqueue("how");
        qt.Enqueue("to");
        qt.Enqueue("create");
        qt.Enqueue("Queue");
        qt.Enqueue("in");
        qt.Enqueue("C#");
  
        Console.Write("After Enqueue Method: ");
          
        // Count property is used to get the
        // number of elements in qt
        Console.WriteLine(qt.Count);
    }
}
输出:
Before Enqueue Method: 0
After Enqueue Method: 8

参考:

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