Stack<T> Stack<T> Stack<T> Stack<T> Class

定義

表示相同特定類型之執行個體的各種大小後進先出 (LIFO) 集合。Represents a variable size last-in-first-out (LIFO) collection of instances of the same specified type.

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

類型參數

T

指定堆疊中元素的類型。Specifies the type of elements in the stack.

繼承
Stack<T>Stack<T>Stack<T>Stack<T>
屬性
實作

範例

下列程式碼範例示範Stack<T>泛型類別的數個方法。The following code example demonstrates several methods of the Stack<T> generic class. 此程式碼範例會建立具有預設容量的字串堆疊, 並Push使用方法將五個字串推送至堆疊。The code example creates a stack of strings with default capacity and uses the Push method to push five strings onto the stack. 堆疊的元素會列舉, 這不會變更堆疊的狀態。The elements of the stack are enumerated, which does not change the state of the stack. Pop方法是用來從堆疊中彈出第一個字串。The Pop method is used to pop the first string off the stack. 方法是用來查看堆疊上的下一個專案, Pop然後使用方法將它關閉。 PeekThe Peek method is used to look at the next item on the stack, and then the Pop method is used to pop it off.

方法是用來建立陣列並將堆疊元素複製到其中, 然後陣列會傳遞Stack<T>至所採用IEnumerable<T>的函式, 並以反轉專案的順序建立堆疊的複本。 ToArrayThe ToArray method is used to create an array and copy the stack elements to it, then the array is passed to the Stack<T> constructor that takes IEnumerable<T>, creating a copy of the stack with the order of the elements reversed. 隨即顯示覆本的元素。The elements of the copy are displayed.

陣列的兩倍會建立堆疊的大小, 而CopyTo方法則是用來複製從陣列中間開始的陣列元素。An array twice the size of the stack is created, and the CopyTo method is used to copy the array elements beginning at the middle of the array. 再次Stack<T>使用此函式來建立堆疊的複本, 並反轉專案的順序, 因此, 這三個 null 元素位於結尾。The Stack<T> constructor is used again to create a copy of the stack with the order of elements reversed; thus, the three null elements are at the end.

方法是用來顯示字串 "四" 位於堆疊的第一個複本中, 在Clear這之後, 方法會Count清除複本, 而屬性會顯示堆疊是空的。 ContainsThe Contains method is used to show that the string "four" is in the first copy of the stack, after which the Clear method clears the copy and the Count property shows that the stack is empty.

using System;
using System.Collections.Generic;

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

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

        Console.WriteLine("\nPopping '{0}'", numbers.Pop());
        Console.WriteLine("Peek at next item to destack: {0}", 
            numbers.Peek());
        Console.WriteLine("Popping '{0}'", numbers.Pop());

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

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

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

        Console.WriteLine("\nstack2.Contains(\"four\") = {0}", 
            stack2.Contains("four"));

        Console.WriteLine("\nstack2.Clear()");
        stack2.Clear();
        Console.WriteLine("\nstack2.Count = {0}", stack2.Count);
    }
}

/* This code example produces the following output:

five
four
three
two
one

Popping 'five'
Peek at next item to destack: four
Popping 'four'

Contents of the first copy:
one
two
three

Contents of the second copy, with duplicates and nulls:
one
two
three




stack2.Contains("four") = False

stack2.Clear()

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

Module Example

    Sub Main

        Dim numbers As New Stack(Of String)
        numbers.Push("one")
        numbers.Push("two")
        numbers.Push("three")
        numbers.Push("four")
        numbers.Push("five")

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

        Console.WriteLine(vbLf & "Popping '{0}'", numbers.Pop())
        Console.WriteLine("Peek at next item to pop: {0}", _
            numbers.Peek())    
        Console.WriteLine("Popping '{0}'", numbers.Pop())

        ' Create another stack, using the ToArray method and the
        ' constructor that accepts an IEnumerable(Of T). Note that
        ' the order of items on the new stack is reversed.
        Dim stack2 As New Stack(Of String)(numbers.ToArray())

        Console.WriteLine(vbLf & "Contents of the first copy:")
        For Each number As String In stack2
            Console.WriteLine(number)
        Next
        
        ' Create an array twice the size of the stack, compensating
        ' for the fact that Visual Basic allocates an extra array 
        ' element. Copy the elements of the stack, starting at the
        ' middle of the array. 
        Dim array2((numbers.Count * 2) - 1) As String
        numbers.CopyTo(array2, numbers.Count)
        
        ' Create a second stack, using the constructor that accepts an
        ' IEnumerable(Of T). The elements are reversed, with the null
        ' elements appearing at the end of the stack when enumerated.
        Dim stack3 As New Stack(Of String)(array2)

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

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

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

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

備註

Stack<T>會實作為陣列。Stack<T> is implemented as an array.

當您需要暫時儲存資訊時, 堆疊和佇列很有用;也就是說, 當您在抓取專案值之後, 可能會想要捨棄元素。Stacks and queues 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. 如果System.Collections.Generic.Stack<T>您需要以相反順序存取訊號, 請使用。Use System.Collections.Generic.Stack<T> if you need to access the information in reverse order.

當您需要System.Collections.Concurrent.ConcurrentQueue<T>同時從多個執行緒存取集合時, 請使用和類型。System.Collections.Concurrent.ConcurrentStack<T>Use the System.Collections.Concurrent.ConcurrentStack<T> and System.Collections.Concurrent.ConcurrentQueue<T> types when you need to access the collection from multiple threads concurrently.

的常見用法System.Collections.Generic.Stack<T>是在呼叫其他程式時保留變數狀態。A common use for System.Collections.Generic.Stack<T> is to preserve variable states during calls to other procedures.

可以在System.Collections.Generic.Stack<T>和其元素上執行三個主要作業:Three main operations can be performed on a System.Collections.Generic.Stack<T> and its elements:

的容量Stack<T>Stack<T>可以保存的元素數目。The capacity of a Stack<T> is the number of elements the Stack<T> can hold. 當專案加入至Stack<T>時, 會視需要重新配置內部陣列, 自動增加容量。As elements are added to a Stack<T>, the capacity is automatically increased as required by reallocating the internal array. 藉由呼叫TrimExcess, 可以降低容量。The capacity can be decreased by calling TrimExcess.

如果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<T>接受null當做參考型別的有效值, 並允許重複的元素。Stack<T> accepts null as a valid value for reference types and allows duplicate elements.

建構函式

Stack<T>() Stack<T>() Stack<T>() Stack<T>()

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

Stack<T>(IEnumerable<T>) Stack<T>(IEnumerable<T>) Stack<T>(IEnumerable<T>) Stack<T>(IEnumerable<T>)

初始化 Stack<T> 類別的新執行個體,其包含從指定之集合複製的元素,且具有容納複製之元素數目的足夠容量。Initializes a new instance of the Stack<T> class that contains elements copied from the specified collection and has sufficient capacity to accommodate the number of elements copied.

Stack<T>(Int32) Stack<T>(Int32) Stack<T>(Int32) Stack<T>(Int32)

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

屬性

Count Count Count Count

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

方法

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

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

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

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

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

從指定的陣列索引處開始,複製 Stack<T> 至現有一維 ArrayCopies the Stack<T> 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()

傳回 Stack<T> 的列舉值。Returns an enumerator for the Stack<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()

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

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

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

Push(T) Push(T) Push(T) Push(T)

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

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

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

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

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

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

如果該數目小於目前容量的 90%,則將容量設為 Stack<T> 中元素的實際數目。Sets the capacity to the actual number of elements in the Stack<T>, if that number is less than 90 percent of current capacity.

TryPeek(T) TryPeek(T) TryPeek(T) TryPeek(T)
TryPop(T) TryPop(T) TryPop(T) TryPop(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 the 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.

只要不修改集合,就可以同時支援多個讀取器。Stack<T>A Stack<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. 若要確保列舉期間的執行緒安全性,您可以在整個列舉期間鎖定集合。To guarantee thread safety during enumeration, you can lock the collection during the entire enumeration. 若要讓多重執行緒能夠存取集合以便進行讀取和寫入,您必須實作自己的同步處理。To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.

另請參閱