Queue<T> Queue<T> Queue<T> Queue<T> Class

定义

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

generic <typename T>
public ref class Queue : System::Collections::Generic::IEnumerable<T>, System::Collections::Generic::IReadOnlyCollection<T>, System::Collections::ICollection
[System.Runtime.InteropServices.ComVisible(false)]
[System.Serializable]
public class Queue<T> : System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.ICollection
type Queue<'T> = class
    interface seq<'T>
    interface ICollection
    interface IReadOnlyCollection<'T>
    interface IEnumerable
Public Class Queue(Of T)
Implements ICollection, IEnumerable(Of T), IReadOnlyCollection(Of T)

类型参数

T

指定队列中元素的类型。Specifies the type of elements in the queue.

继承
Queue<T>Queue<T>Queue<T>Queue<T>
属性
实现

示例

下面的代码示例演示了Queue<T>泛型类的几个方法。The following code example demonstrates several methods of the Queue<T> generic class. 此代码示例创建具有默认容量的字符串队列, 并使用Enqueue方法将五个字符串进行排队。The code example creates a queue of strings with default capacity and uses the Enqueue method to queue five strings. 枚举队列的元素, 而不会更改队列的状态。The elements of the queue are enumerated, which does not change the state of the queue. Dequeue方法用于取消对第一个字符串的排队。The Dequeue method is used to dequeue the first string. 方法用于查看队列中的下一项, Dequeue然后使用方法将其取消排队。 PeekThe Peek method is used to look at the next item in the queue, and then the Dequeue method is used to dequeue it.

方法用于创建数组, 并将队列元素复制到该数组, 然后将数组传递Queue<T>给采用IEnumerable<T>的构造函数, 创建队列的副本。 ToArrayThe ToArray method is used to create an array and copy the queue elements to it, then the array is passed to the Queue<T> constructor that takes IEnumerable<T>, creating a copy of the queue. 将显示副本的元素。The elements of the copy are displayed.

创建队列大小两倍的数组, 并CopyTo使用方法从数组中间开始复制数组元素。An array twice the size of the queue is created, and the CopyTo method is used to copy the array elements beginning at the middle of the array. 在开始时, 将再次使用构造函数来创建包含三个null元素的队列的第二个副本。Queue<T>The Queue<T> constructor is used again to create a second copy of the queue containing three null elements at the beginning.

方法用于显示字符串 "四" 位于队列的第一个副本中, 在Clear此之后, 方法会Count清除副本, 属性显示该队列为空。 ContainsThe Contains method is used to show that the string "four" is in the first copy of the queue, after which the Clear method clears the copy and the Count property shows that the queue is empty.

using System;
using System.Collections.Generic;

class Example
{
    public static void Main()
    {
        Queue<string> numbers = new Queue<string>();
        numbers.Enqueue("one");
        numbers.Enqueue("two");
        numbers.Enqueue("three");
        numbers.Enqueue("four");
        numbers.Enqueue("five");

        // A queue can be enumerated without disturbing its contents.
        foreach( string number in numbers )
        {
            Console.WriteLine(number);
        }

        Console.WriteLine("\nDequeuing '{0}'", numbers.Dequeue());
        Console.WriteLine("Peek at next item to dequeue: {0}", 
            numbers.Peek());
        Console.WriteLine("Dequeuing '{0}'", numbers.Dequeue());

        // Create a copy of the queue, using the ToArray method and the
        // constructor that accepts an IEnumerable<T>.
        Queue<string> queueCopy = new Queue<string>(numbers.ToArray());

        Console.WriteLine("\nContents of the first copy:");
        foreach( string number in queueCopy )
        {
            Console.WriteLine(number);
        }
        
        // Create an array twice the size of the queue and copy the
        // elements of the queue, starting at the middle of the 
        // array. 
        string[] array2 = new string[numbers.Count * 2];
        numbers.CopyTo(array2, numbers.Count);
        
        // Create a second queue, using the constructor that accepts an
        // IEnumerable(Of T).
        Queue<string> queueCopy2 = new Queue<string>(array2);

        Console.WriteLine("\nContents of the second copy, with duplicates and nulls:");
        foreach( string number in queueCopy2 )
        {
            Console.WriteLine(number);
        }

        Console.WriteLine("\nqueueCopy.Contains(\"four\") = {0}", 
            queueCopy.Contains("four"));

        Console.WriteLine("\nqueueCopy.Clear()");
        queueCopy.Clear();
        Console.WriteLine("\nqueueCopy.Count = {0}", queueCopy.Count);
    }
}

/* This code example produces the following output:

one
two
three
four
five

Dequeuing 'one'
Peek at next item to dequeue: two
Dequeuing 'two'

Contents of the copy:
three
four
five

Contents of the second copy, with duplicates and nulls:



three
four
five

queueCopy.Contains("four") = True

queueCopy.Clear()

queueCopy.Count = 0
 */
Imports System
Imports System.Collections.Generic

Module Example

    Sub Main

        Dim numbers As New Queue(Of String)
        numbers.Enqueue("one")
        numbers.Enqueue("two")
        numbers.Enqueue("three")
        numbers.Enqueue("four")
        numbers.Enqueue("five")

        ' A queue can be enumerated without disturbing its contents.
        For Each number As String In numbers
            Console.WriteLine(number)
        Next

        Console.WriteLine(vbLf & "Dequeuing '{0}'", numbers.Dequeue())
        Console.WriteLine("Peek at next item to dequeue: {0}", _
            numbers.Peek())    
        Console.WriteLine("Dequeuing '{0}'", numbers.Dequeue())

        ' Create a copy of the queue, using the ToArray method and the
        ' constructor that accepts an IEnumerable(Of T).
        Dim queueCopy As New Queue(Of String)(numbers.ToArray())

        Console.WriteLine(vbLf & "Contents of the first copy:")
        For Each number As String In queueCopy
            Console.WriteLine(number)
        Next
        
        ' Create an array twice the size of the queue, compensating
        ' for the fact that Visual Basic allocates an extra array 
        ' element. Copy the elements of the queue, starting at the
        ' middle of the array. 
        Dim array2((numbers.Count * 2) - 1) As String
        numbers.CopyTo(array2, numbers.Count)
        
        ' Create a second queue, using the constructor that accepts an
        ' IEnumerable(Of T).
        Dim queueCopy2 As New Queue(Of String)(array2)

        Console.WriteLine(vbLf & _
            "Contents of the second copy, with duplicates and nulls:")
        For Each number As String In queueCopy2
            Console.WriteLine(number)
        Next

        Console.WriteLine(vbLf & "queueCopy.Contains(""four"") = {0}", _
            queueCopy.Contains("four"))

        Console.WriteLine(vbLf & "queueCopy.Clear()")
        queueCopy.Clear()
        Console.WriteLine(vbLf & "queueCopy.Count = {0}", _
            queueCopy.Count)
    End Sub
End Module

' This code example produces the following output:
'
'one
'two
'three
'four
'five
'
'Dequeuing 'one'
'Peek at next item to dequeue: two
'
'Dequeuing 'two'
'
'Contents of the copy:
'three
'four
'five
'
'Contents of the second copy, with duplicates and nulls:
'
'
'
'three
'four
'five
'
'queueCopy.Contains("four") = True
'
'queueCopy.Clear()
'
'queueCopy.Count = 0

注解

此类将泛型队列实现为循环数组。This class implements a generic queue as a circular array. 存储在中的Queue<T>对象将在一端插入并从另一个中删除。Objects stored in a Queue<T> are inserted at one end and removed from the other. 如果需要临时存储信息, 则队列和堆栈非常有用;也就是说, 当你可能想要在检索元素值后丢弃该元素时。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<T>需要以存储在集合中的相同顺序访问该信息, 请使用。Use Queue<T> if you need to access the information in the same order that it is stored in the collection. 如果Stack<T>需要按相反的顺序访问该信息, 请使用。Use Stack<T> 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<T>及其元素执行三个主要操作:Three main operations can be performed on a Queue<T> and its elements:

的容量Queue<T>Queue<T>可容纳的元素数。The capacity of a Queue<T> is the number of elements the Queue<T> can hold. 当向添加元素时Queue<T>, 将根据需要通过重新分配内部数组来自动增加容量。As elements are added to a Queue<T>, the capacity is automatically increased as required by reallocating the internal array. 可以通过调用TrimExcess来减少容量。The capacity can be decreased by calling TrimExcess.

Queue<T>接受null作为引用类型的有效值, 并允许重复元素。Queue<T> accepts null as a valid value for reference types and allows duplicate elements.

构造函数

Queue<T>() Queue<T>() Queue<T>() Queue<T>()

初始化 Queue<T> 类的新实例,该实例为空并且具有默认初始容量。Initializes a new instance of the Queue<T> class that is empty and has the default initial capacity.

Queue<T>(IEnumerable<T>) Queue<T>(IEnumerable<T>) Queue<T>(IEnumerable<T>) Queue<T>(IEnumerable<T>)

初始化 Queue<T> 类的新实例,该实例包含从指定集合复制的元素并且具有足够的容量来容纳所复制的元素。Initializes a new instance of the Queue<T> class that contains elements copied from the specified collection and has sufficient capacity to accommodate the number of elements copied.

Queue<T>(Int32) Queue<T>(Int32) Queue<T>(Int32) Queue<T>(Int32)

初始化 Queue<T> 类的新实例,该实例为空并且具有指定的初始容量。Initializes a new instance of the Queue<T> class that is empty and has the specified initial capacity.

属性

Count Count Count Count

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

方法

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

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

Contains(T) Contains(T) Contains(T) Contains(T)

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

CopyTo(T[], Int32) CopyTo(T[], Int32) CopyTo(T[], Int32) CopyTo(T[], Int32)

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

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

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

Enqueue(T) Enqueue(T) Enqueue(T) Enqueue(T)

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

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<T> 的枚举数。Returns an enumerator that iterates through the Queue<T>.

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<T> 开始处的对象但不将其移除。Returns the object at the beginning of the Queue<T> without removing it.

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

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

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

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

(Inherited from Object)
TrimExcess() TrimExcess() TrimExcess() TrimExcess()

如果元素数小于当前容量的 90%,将容量设置为 Queue<T> 中的实际元素数。Sets the capacity to the actual number of elements in the Queue<T>, if that number is less than 90 percent of current capacity.

TryDequeue(T) TryDequeue(T) TryDequeue(T) TryDequeue(T)
TryPeek(T) TryPeek(T) TryPeek(T) TryPeek(T)

显式界面实现

ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32)

从特定的 ICollection 索引开始,将 Array 的元素复制到一个 Array 中。Copies the elements of the ICollection to an Array, starting at a particular Array index.

ICollection.IsSynchronized ICollection.IsSynchronized ICollection.IsSynchronized ICollection.IsSynchronized

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

ICollection.SyncRoot ICollection.SyncRoot ICollection.SyncRoot ICollection.SyncRoot

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

IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator()

返回循环访问集合的枚举数。Returns an enumerator that iterates through a collection.

IEnumerable<T>.GetEnumerator() IEnumerable<T>.GetEnumerator() IEnumerable<T>.GetEnumerator() IEnumerable<T>.GetEnumerator()

返回循环访问集合的枚举数。Returns an enumerator that iterates through a collection.

扩展方法

CopyToDataTable<T>(IEnumerable<T>) CopyToDataTable<T>(IEnumerable<T>) CopyToDataTable<T>(IEnumerable<T>) CopyToDataTable<T>(IEnumerable<T>)

在给定其泛型参数 TDataTable 的输入 DataRow 对象的情况下,返回包含 IEnumerable<T> 对象副本的 DataRowReturns a DataTable that contains copies of the DataRow objects, given an input IEnumerable<T> object where the generic parameter T is DataRow.

CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption)

在给定其泛型参数 TDataRow 的输入 DataTable 对象的情况下,将 IEnumerable<T> 对象复制到指定的 DataRowCopies DataRow objects to the specified DataTable, given an input IEnumerable<T> object where the generic parameter T is DataRow.

CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler)

在给定其泛型参数 TDataRow 的输入 DataTable 对象的情况下,将 IEnumerable<T> 对象复制到指定的 DataRowCopies DataRow objects to the specified DataTable, given an input IEnumerable<T> object where the generic parameter T is DataRow.

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.

Ancestors<T>(IEnumerable<T>) Ancestors<T>(IEnumerable<T>) Ancestors<T>(IEnumerable<T>) Ancestors<T>(IEnumerable<T>)

返回元素集合,其中包含源集合中每个节点的上级。Returns a collection of elements that contains the ancestors of every node in the source collection.

Ancestors<T>(IEnumerable<T>, XName) Ancestors<T>(IEnumerable<T>, XName) Ancestors<T>(IEnumerable<T>, XName) Ancestors<T>(IEnumerable<T>, XName)

返回经过筛选的元素集合,其中包含源集合中每个节点的上级。Returns a filtered collection of elements that contains the ancestors of every node in the source collection. 集合中仅包括具有匹配 XName 的元素。Only elements that have a matching XName are included in the collection.

DescendantNodes<T>(IEnumerable<T>) DescendantNodes<T>(IEnumerable<T>) DescendantNodes<T>(IEnumerable<T>) DescendantNodes<T>(IEnumerable<T>)

返回源集合中每个文档和元素的子代节点的集合。Returns a collection of the descendant nodes of every document and element in the source collection.

Descendants<T>(IEnumerable<T>) Descendants<T>(IEnumerable<T>) Descendants<T>(IEnumerable<T>) Descendants<T>(IEnumerable<T>)

返回元素集合,其中包含源集合中每个元素和文档的子代元素。Returns a collection of elements that contains the descendant elements of every element and document in the source collection.

Descendants<T>(IEnumerable<T>, XName) Descendants<T>(IEnumerable<T>, XName) Descendants<T>(IEnumerable<T>, XName) Descendants<T>(IEnumerable<T>, XName)

返回经过筛选的元素集合,其中包含源集合中每个元素和文档的子代元素。Returns a filtered collection of elements that contains the descendant elements of every element and document in the source collection. 集合中仅包括具有匹配 XName 的元素。Only elements that have a matching XName are included in the collection.

Elements<T>(IEnumerable<T>) Elements<T>(IEnumerable<T>) Elements<T>(IEnumerable<T>) Elements<T>(IEnumerable<T>)

返回源集合中每个元素和文档的子元素的集合。Returns a collection of the child elements of every element and document in the source collection.

Elements<T>(IEnumerable<T>, XName) Elements<T>(IEnumerable<T>, XName) Elements<T>(IEnumerable<T>, XName) Elements<T>(IEnumerable<T>, XName)

返回源集合中经过筛选的每个元素和文档的子元素集合。Returns a filtered collection of the child elements of every element and document in the source collection. 集合中仅包括具有匹配 XName 的元素。Only elements that have a matching XName are included in the collection.

InDocumentOrder<T>(IEnumerable<T>) InDocumentOrder<T>(IEnumerable<T>) InDocumentOrder<T>(IEnumerable<T>) InDocumentOrder<T>(IEnumerable<T>)

返回节点集合(其中包含源集合中的所有节点),并按文档顺序排列。Returns a collection of nodes that contains all nodes in the source collection, sorted in document order.

Nodes<T>(IEnumerable<T>) Nodes<T>(IEnumerable<T>) Nodes<T>(IEnumerable<T>) Nodes<T>(IEnumerable<T>)

返回源集合中每个文档和元素的子节点集合。Returns a collection of the child nodes of every document and element in the source collection.

Remove<T>(IEnumerable<T>) Remove<T>(IEnumerable<T>) Remove<T>(IEnumerable<T>) Remove<T>(IEnumerable<T>)

将源集合中的每个节点从其父节点中移除。Removes every node in the source collection from its parent node.

适用于

线程安全性

此类型的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<T>A Queue<T> can support multiple readers concurrently, as long as the collection is not modified. 尽管如此, 枚举集合本身并不是一个线程安全的过程。Even so, enumerating through a collection is intrinsically not a thread-safe procedure. 对于线程安全队列, 请参阅ConcurrentQueue<T>For a thread-safe queue, see ConcurrentQueue<T>.