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

定義

表示物件的先進先出 (FIFO) 集合。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. Peek方法來查看佇列中下一個項目,然後Dequeue方法用來清除佇列。The Peek method is used to look at the next item in the queue, and then the Dequeue method is used to dequeue it.

ToArray方法用來建立陣列,並將佇列項目複製到它,則陣列傳遞至Queue<T>建構函式IEnumerable<T>,建立佇列的複本。The 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. Queue<T>建構函式會再次用來建立包含在開頭的三個 null 項目佇列的第二個複本。The Queue<T> constructor is used again to create a second copy of the queue containing three null elements at the beginning.

Contains方法用來顯示"four"的字串是在佇列中的第一個複本之後Clear方法會清除複製和Count屬性會顯示佇列是空的。The 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. 藉由呼叫,您可以減少容量TrimExcessThe 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> 項目至現有一維 ArrayCopies 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 的淺層複本 (Shallow Copy)。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 的項目複製到 ArrayCopies 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.

Extension Methods

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

傳回DataTable,其中包含副本DataRow物件,指定輸入IEnumerable<T>物件其中泛型參數TDataRowReturns 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)

複本DataRow至指定的物件DataTable,根據輸入IEnumerable<T>物件其中泛型參數TDataRowCopies 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)

複本DataRow至指定的物件DataTable,根據輸入IEnumerable<T>物件其中泛型參數TDataRowCopies 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)

將轉換IEnumerableIQueryableConverts 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.

AQueue<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>.