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. 方法是用來查看佇列中的下一個專案, 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. 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.

方法是用來顯示在佇列的第一份複本中,字串 "四" 是在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.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> 元素至現有一維 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.

擴充方法

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

根據輸入 DataTable 物件 (其中泛型參數 TDataRow) 傳回包含 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)

根據輸入 DataRow 物件 (其中泛型參數 TDataTable),將 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)

根據輸入 DataRow 物件 (其中泛型參數 TDataTable),將 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>.