Queue Queue Queue Queue Class

定義

表示物件的先進先出 (FIFO) 集合。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 元素至現有一維 ArrayCopies 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 的淺層複本 (Shallow Copy)。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)

傳回包裝原始佇列並且為安全執行緒的新 QueueReturns 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.

另請參閱