Queue Queue Queue Queue Class

定义

表示对象的先进先出集合。Represents a first-in, first-out collection of objects.

public ref class Queue : ICloneable, System::Collections::ICollection
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public class Queue : ICloneable, System.Collections.ICollection
type Queue = class
    interface ICollection
    interface ICloneable
    interface IEnumerable
Public Class Queue
Implements ICloneable, ICollection
继承
QueueQueueQueueQueue
属性
实现

示例

下面的示例演示如何创建值并将其添加到Queue中, 以及如何打印出其值。The following example shows how to create and add values to a Queue and how to print out its values.

using namespace System;
using namespace System::Collections;
void PrintValues( IEnumerable^ myCollection );
int main()
{
   
   // Creates and initializes a new Queue.
   Queue^ myQ = gcnew Queue;
   myQ->Enqueue( "Hello" );
   myQ->Enqueue( "World" );
   myQ->Enqueue( "!" );
   
   // Displays the properties and values of the Queue.
   Console::WriteLine( "myQ" );
   Console::WriteLine( "\tCount:    {0}", myQ->Count );
   Console::Write( "\tValues:" );
   PrintValues( myQ );
}

void PrintValues( IEnumerable^ myCollection )
{
   IEnumerator^ myEnum = myCollection->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      Object^ obj = safe_cast<Object^>(myEnum->Current);
      Console::Write( "    {0}", obj );
   }

   Console::WriteLine();
}

/* 
 This code produces the following output.
 
 myQ
     Count:    3
     Values:    Hello    World    !
*/
 using System;
 using System.Collections;
 public class SamplesQueue  {
 
    public static void Main()  {
 
       // Creates and initializes a new Queue.
       Queue myQ = new Queue();
       myQ.Enqueue("Hello");
       myQ.Enqueue("World");
       myQ.Enqueue("!");
 
       // Displays the properties and values of the Queue.
       Console.WriteLine( "myQ" );
       Console.WriteLine( "\tCount:    {0}", myQ.Count );
       Console.Write( "\tValues:" );
       PrintValues( myQ );
    }
 
 
    public static void PrintValues( IEnumerable myCollection )  {
       foreach ( Object obj in myCollection )
          Console.Write( "    {0}", obj );
       Console.WriteLine();
    }
 }
 /* 
 This code produces the following output.
 
 myQ
     Count:    3
     Values:    Hello    World    !
*/ 
Imports System.Collections

Public Class SamplesQueue

    Public Shared Sub Main()

        ' Creates and initializes a new Queue.
        Dim myQ As New Queue()
        myQ.Enqueue("Hello")
        myQ.Enqueue("World")
        myQ.Enqueue("!")

        ' Displays the properties and values of the Queue.
        Console.WriteLine("myQ")
        Console.WriteLine("    Count:    {0}", myQ.Count)
        Console.Write("    Values:")
        PrintValues(myQ)

    End Sub 'Main

    Public Shared Sub PrintValues(myCollection As IEnumerable)
        Dim obj As [Object]
        For Each obj In  myCollection
            Console.Write("    {0}", obj)
        Next obj
        Console.WriteLine()
    End Sub 'PrintValues

End Class 'SamplesQueue


' This code produces the following output.
' 
' myQ
'     Count:    3
'     Values:    Hello    World    !

注解

此类将队列实现为循环数组。This class implements a queue as a circular array. 存储在中的Queue对象将在一端插入并从另一个中删除。Objects stored in a Queue are inserted at one end and removed from the other.

重要

不建议使用Queue类进行新的开发。We don't recommend that you use the Queue class for new development. 相反, 我们建议使用泛型Queue<T>类。Instead, we recommend that you use the generic Queue<T> class. 有关详细信息, 请参阅 GitHub 上不应使用非泛型集合For more information, see Non-generic collections shouldn't be used on GitHub.

如果需要临时存储信息, 则队列和堆栈非常有用;也就是说, 当你可能想要在检索元素值后丢弃该元素时。Queues and stacks are useful when you need temporary storage for information; that is, when you might want to discard an element after retrieving its value. 如果Queue需要以存储在集合中的相同顺序访问该信息, 请使用。Use Queue if you need to access the information in the same order that it is stored in the collection. 如果Stack需要按相反的顺序访问该信息, 请使用。Use Stack if you need to access the information in reverse order. 如果ConcurrentQueue<T>需要ConcurrentStack<T>从多个线程同时访问集合, 请使用或。Use ConcurrentQueue<T> or ConcurrentStack<T> if you need to access the collection from multiple threads concurrently.

可以对Queue及其元素执行三个主要操作:Three main operations can be performed on a Queue and its elements:

  • Enqueue将一个元素添加到的末尾QueueEnqueue adds an element to the end of the Queue.

  • Dequeue从的开头Queue移除最旧的元素。Dequeue removes the oldest element from the start of the Queue.

  • Peek返回位于开头Queue的最早的元素, 但不将其Queue从中移除。Peek returns the oldest element that is at the start of the Queue but does not remove it from the Queue.

的容量QueueQueue可容纳的元素数。The capacity of a Queue is the number of elements the Queue can hold. 向添加元素时Queue, 会根据需要通过重新分配来自动增加容量。As elements are added to a Queue, the capacity is automatically increased as required through reallocation. 可以通过调用TrimToSize来减少容量。The capacity can be decreased by calling TrimToSize.

增长系数是在需要更大容量时, 当前容量乘以的数值。The growth factor is the number by which the current capacity is multiplied when a greater capacity is required. 此增长因子是在构造时Queue确定的。The growth factor is determined when the Queue is constructed. 默认增长系数为2.0。The default growth factor is 2.0. 无论增长系数如何Queue , 的容量将始终至少增加四个。The capacity of the Queue will always increase by at least a minimum of four, regardless of the growth factor. 例如, 如果需要Queue更大的容量, 则增长系数为1.0 的将始终增加四倍。For example, a Queue with a growth factor of 1.0 will always increase in capacity by four when a greater capacity is required.

Queue接受null作为有效值, 并允许重复元素。Queue accepts null as a valid value and allows duplicate elements.

有关此集合的泛型版本, 请参阅System.Collections.Generic.Queue<T>For the generic version of this collection, see System.Collections.Generic.Queue<T>

构造函数

Queue() Queue() Queue() Queue()

初始化 Queue 类的新实例,该实例为空,具有默认初始容量并使用默认增长因子。Initializes a new instance of the Queue class that is empty, has the default initial capacity, and uses the default growth factor.

Queue(ICollection) Queue(ICollection) Queue(ICollection) Queue(ICollection)

初始化 Queue 类的新实例,该实例包含从指定集合复制的元素,具有与所复制的元素数相同的初始容量并使用默认增长因子。Initializes a new instance of the Queue class that contains elements copied from the specified collection, has the same initial capacity as the number of elements copied, and uses the default growth factor.

Queue(Int32) Queue(Int32) Queue(Int32) Queue(Int32)

初始化 Queue 类的新实例,该实例为空,具有指定的初始容量并使用默认增长因子。Initializes a new instance of the Queue class that is empty, has the specified initial capacity, and uses the default growth factor.

Queue(Int32, Single) Queue(Int32, Single) Queue(Int32, Single) Queue(Int32, Single)

初始化 Queue 类的新实例,该实例为空,具有指定的初始容量并使用指定的增长因子。Initializes a new instance of the Queue class that is empty, has the specified initial capacity, and uses the specified growth factor.

属性

Count Count Count Count

获取 Queue 中包含的元素数。Gets the number of elements contained in the Queue.

IsSynchronized IsSynchronized IsSynchronized IsSynchronized

获取一个值,该值指示是否同步对 Queue 的访问(线程安全)。Gets a value indicating whether access to the Queue is synchronized (thread safe).

SyncRoot SyncRoot SyncRoot SyncRoot

获取可用于同步对 Queue 的访问的对象。Gets an object that can be used to synchronize access to the Queue.

方法

Clear() Clear() Clear() Clear()

Queue 中移除所有对象。Removes all objects from the Queue.

Clone() Clone() Clone() Clone()

创建 Queue 的浅表副本。Creates a shallow copy of the Queue.

Contains(Object) Contains(Object) Contains(Object) Contains(Object)

确定某元素是否在 Queue 中。Determines whether an element is in the Queue.

CopyTo(Array, Int32) CopyTo(Array, Int32) CopyTo(Array, Int32) CopyTo(Array, Int32)

从指定数组索引开始将 Queue 元素复制到现有一维 Array 中。Copies the Queue elements to an existing one-dimensional Array, starting at the specified array index.

Dequeue() Dequeue() Dequeue() Dequeue()

移除并返回位于 Queue 开始处的对象。Removes and returns the object at the beginning of the Queue.

Enqueue(Object) Enqueue(Object) Enqueue(Object) Enqueue(Object)

将对象添加到 Queue 的结尾处。Adds an object to the end of the Queue.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetEnumerator() GetEnumerator() GetEnumerator() GetEnumerator()

返回循环访问 Queue 的枚举数。Returns an enumerator that iterates through the Queue.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

获取当前实例的 TypeGets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
Peek() Peek() Peek() Peek()

返回位于 Queue 开始处的对象但不将其移除。Returns the object at the beginning of the Queue without removing it.

Synchronized(Queue) Synchronized(Queue) Synchronized(Queue) Synchronized(Queue)

返回一个新的 Queue,它将包装原始队列,并且是线程安全的。Returns a new Queue that wraps the original queue, and is thread safe.

ToArray() ToArray() ToArray() ToArray()

Queue 元素复制到新数组。Copies the Queue elements to a new array.

ToString() ToString() ToString() ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(Inherited from Object)
TrimToSize() TrimToSize() TrimToSize() TrimToSize()

将容量设置为 Queue 中元素的实际数目。Sets the capacity to the actual number of elements in the Queue.

扩展方法

Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable)

IEnumerable 的元素强制转换为指定的类型。Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable)

根据指定类型筛选 IEnumerable 的元素。Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable)

启用查询的并行化。Enables parallelization of a query.

AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable)

IEnumerable 转换为 IQueryableConverts an IEnumerable to an IQueryable.

适用于

线程安全性

此类型的Shared公共静态 (在 Visual Basic) 成员是线程安全的。Public static (Shared in Visual Basic) members of this type are thread safe. 但不保证所有实例成员都是线程安全的。Any instance members are not guaranteed to be thread safe.

若要保证的线程安全Queue, 必须通过Synchronized(Queue)方法返回的包装执行所有操作。To guarantee the thread safety of the Queue, all operations must be done through the wrapper returned by the Synchronized(Queue) method.

枚举整个集合本质上不是一个线程安全的过程。Enumerating through a collection is intrinsically not a thread-safe procedure. 即使某个集合已同步,其他线程仍可以修改该集合,这会导致枚举数引发异常。Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. 若要确保枚举过程中的线程安全性,可以在整个枚举期间锁定集合,或者捕获由其他线程进行的更改所导致的异常。To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

另请参阅