Stack Stack Stack Stack Class


表示簡單之物件的後進先出 (Last-In First-Out,LIFO) 非泛型集合。Represents a simple last-in-first-out (LIFO) non-generic collection of objects.

public ref class Stack : ICloneable, System::Collections::ICollection
public class Stack : ICloneable, System.Collections.ICollection
type Stack = class
    interface ICollection
    interface ICloneable
    interface IEnumerable
Public Class Stack
Implements ICloneable, ICollection


下列範例示範如何建立和新增值至堆疊, 以及如何顯示其值。The following example shows how to create and add values to a Stack and how to display its values.

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

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


 This code produces the following output.
     Count:    3
     Values:    !    World    Hello
using System;
using System.Collections;
public class SamplesStack  {

   public static void Main()  {

      // Creates and initializes a new Stack.
      Stack myStack = new Stack();

      // Displays the properties and values of the Stack.
      Console.WriteLine( "myStack" );
      Console.WriteLine( "\tCount:    {0}", myStack.Count );
      Console.Write( "\tValues:" );
      PrintValues( myStack );

   public static void PrintValues( IEnumerable myCollection )  {
      foreach ( Object obj in myCollection )
         Console.Write( "    {0}", obj );


This code produces the following output.

    Count:    3
    Values:    !    World    Hello

Imports System.Collections

Public Class SamplesStack    
    Public Shared Sub Main()
        ' Creates and initializes a new Stack.
        Dim myStack As New Stack()
        ' Displays the properties and values of the Stack.
        Console.WriteLine(ControlChars.Tab & "Count:    {0}", myStack.Count)
        Console.Write(ControlChars.Tab & "Values:")
    End Sub
    Public Shared Sub PrintValues(myCollection As IEnumerable)
        Dim obj As [Object]
        For Each obj In  myCollection
            Console.Write("    {0}", obj)
        Next obj
    End Sub

End Class

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


的容量StackStack可以保存的元素數目。The capacity of a Stack is the number of elements the Stack can hold. 當專案新增至時Stack, 會視需要透過重新配置來自動增加容量。As elements are added to a Stack, the capacity is automatically increased as required through reallocation.


我們不建議您將類別用於Stack新的開發。We don't recommend that you use the Stack class for new development. 相反地, 我們建議您使用泛型System.Collections.Generic.Stack<T>類別。Instead, we recommend that you use the generic System.Collections.Generic.Stack<T> class. 如需詳細資訊, 請參閱不應在 GitHub 上使用非泛型集合For more information, see Non-generic collections shouldn't be used on GitHub.

如果Count小於堆疊的容量, Push則為 O (1) 運算。If Count is less than the capacity of the stack, Push is an O(1) operation. 如果需要增加容量以容納新Push的專案, 則會變成 O (n) 運算, 其中nCountIf the capacity needs to be increased to accommodate the new element, Push becomes an O(n) operation, where n is Count. Pop是 O (1) 運算。Pop is an O(1) operation.

Stack接受null做為有效的值, 並允許重複的元素。Stack accepts null as a valid value and allows duplicate elements.


Stack() Stack() Stack() Stack()

初始化 Stack 類別的新執行個體,這個執行個體為空白且具有預設的初始容量。Initializes a new instance of the Stack class that is empty and has the default initial capacity.

Stack(ICollection) Stack(ICollection) Stack(ICollection) Stack(ICollection)

初始化 Stack 類別的新執行個體,其含有從指定的集合複製過來的元素且具有與複製的元素數一樣的初始容量。Initializes a new instance of the Stack class that contains elements copied from the specified collection and has the same initial capacity as the number of elements copied.

Stack(Int32) Stack(Int32) Stack(Int32) Stack(Int32)

初始化 Stack 類別的新執行個體,其為空白且具有指定的初始容量或預設的初始容量 (兩者中較大的那一個)。Initializes a new instance of the Stack class that is empty and has the specified initial capacity or the default initial capacity, whichever is greater.


Count Count Count Count

取得 Stack 中所包含的項目數。Gets the number of elements contained in the Stack.

IsSynchronized IsSynchronized IsSynchronized IsSynchronized

取得值,這個值表示對 Stack 的存取是否同步 (安全執行緒)。Gets a value indicating whether access to the Stack is synchronized (thread safe).

SyncRoot SyncRoot SyncRoot SyncRoot

取得可用以同步存取 Stack 的物件。Gets an object that can be used to synchronize access to the Stack.


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

Stack 移除所有物件。Removes all objects from the Stack.

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

建立 Stack 的淺層複本。Creates a shallow copy of the Stack.

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

判斷某項目是否在 Stack 中。Determines whether an element is in the Stack.

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

從指定的陣列索引處開始,複製 Stack 至現有一維 ArrayCopies the Stack to an existing one-dimensional Array, starting at the specified array index.

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()

傳回 IEnumeratorStackReturns an IEnumerator for the Stack.

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()

傳回 Stack 頂端的物件而不需移除它。Returns the object at the top of the Stack without removing it.

Pop() Pop() Pop() Pop()

移除並傳回在 Stack 頂端的物件。Removes and returns the object at the top of the Stack.

Push(Object) Push(Object) Push(Object) Push(Object)

將物件插入 Stack 的頂端。Inserts an object at the top of the Stack.

Synchronized(Stack) Synchronized(Stack) Synchronized(Stack) Synchronized(Stack)

傳回 Stack 同步處理的 (安全執行緒) 包裝函式。Returns a synchronized (thread safe) wrapper for the Stack.

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

複製 Stack 至新陣列。Copies the Stack to a new array.

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

傳回代表目前物件的字串。Returns a string that represents the current object.

(Inherited from Object)


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.

為了保證的執行緒安全性Stack, 所有作業都必須透過Synchronized(Stack)方法所傳回的包裝函式來完成。To guarantee the thread safety of the Stack, all operations must be done through the wrapper returned by the Synchronized(Stack) 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.