Stack<T> 類別
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
表示相同特定類型之執行個體的各種大小後進先出 (LIFO) 集合。
generic <typename T>
public ref class Stack : System::Collections::Generic::IEnumerable<T>, System::Collections::Generic::IReadOnlyCollection<T>, System::Collections::ICollection
generic <typename T>
public ref class Stack : System::Collections::Generic::IEnumerable<T>, System::Collections::ICollection
public class Stack<T> : 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.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
public class Stack<T> : System.Collections.Generic.IEnumerable<T>, System.Collections.ICollection
type Stack<'T> = class
interface seq<'T>
interface IEnumerable
interface IReadOnlyCollection<'T>
interface ICollection
[<System.Runtime.InteropServices.ComVisible(false)>]
[<System.Serializable>]
type Stack<'T> = class
interface seq<'T>
interface ICollection
interface IEnumerable
[<System.Runtime.InteropServices.ComVisible(false)>]
[<System.Serializable>]
type Stack<'T> = class
interface seq<'T>
interface IEnumerable
interface ICollection
interface IReadOnlyCollection<'T>
type Stack<'T> = class
interface seq<'T>
interface ICollection
interface IEnumerable
Public Class Stack(Of T)
Implements ICollection, IEnumerable(Of T), IReadOnlyCollection(Of T)
Public Class Stack(Of T)
Implements ICollection, IEnumerable(Of T)
類型參數
- T
指定堆疊中項目的類型。
- 繼承
-
Stack<T>
- 屬性
- 實作
範例
下列程式代碼範例示範泛型類別的 Stack<T> 數種方法。 此程式代碼範例會建立具有預設容量的字串堆疊,並使用 Push 方法將五個字串推送至堆疊。 會列舉堆疊的專案,而不會變更堆疊的狀態。 方法 Pop 可用來從堆疊取出第一個字串。 方法 Peek 可用來查看堆疊上的下一個專案,然後使用 Pop 方法將其彈出。
方法 ToArray 可用來建立數位,並將堆疊元素複製到其中,然後將數位傳遞至 Stack<T> 採用 IEnumerable<T>的建構函式,並使用反轉元素的順序建立堆疊的複本。 隨即顯示複本的專案。
建立堆疊大小的兩倍陣列,並使用 CopyTo 方法複製陣列元素,從陣列中間開始。 建 Stack<T> 構函式會再次用來建立堆疊的複本,並反轉元素的順序;因此,這三個 Null 元素位於結尾。
方法 Contains 用來顯示字串 「four」 位於堆疊的第一個複本中,之後 Clear 方法會清除複本,而 Count 屬性顯示堆疊是空的。
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
*/
open System
open System.Collections.Generic
let numbers = Stack()
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 number in numbers do
printfn $"{number}"
printfn $"\nPopping '{numbers.Pop()}'"
printfn $"Peek at next item to destack: {numbers.Peek()}"
numbers.Peek() |> ignore
printfn $"Popping '{numbers.Pop()}'"
// Create a copy of the stack, using the ToArray method and the
// constructor that accepts an IEnumerable<T>.
let stack2 = numbers.ToArray() |> Stack
printfn "\nContents of the first copy:"
for number in stack2 do
printfn $"{number}"
// Create an array twice the size of the stack and copy the
// elements of the stack, starting at the middle of the
// array.
let array2 = numbers.Count * 2 |> Array.zeroCreate
numbers.CopyTo(array2, numbers.Count)
// Create a second stack, using the constructor that accepts an
// IEnumerable(Of T).
let stack3 = Stack array2
printfn "\nContents of the second copy, with duplicates and nulls:"
for number in stack3 do
printfn $"{number}"
printfn
$"""
stack2.Contains "four" = {stack2.Contains "four"}"""
printfn "\nstack2.Clear()"
stack2.Clear()
printfn $"\nstack2.Count = {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.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> 會實作為陣列。
當您需要暫存記憶體以取得資訊時,堆疊和佇列很有用;也就是說,當您想要在擷取元素的值之後捨棄專案時。 如果您需要以儲存在集合中的相同順序存取資訊,請使用 Queue<T> 。 如果您需要以反向順序存取資訊,請使用 System.Collections.Generic.Stack<T> 。
System.Collections.Concurrent.ConcurrentStack<T>當您需要同時從多個線程存取集合時,請使用和 System.Collections.Concurrent.ConcurrentQueue<T> 類型。
的常見用途 System.Collections.Generic.Stack<T> 是在呼叫其他程序期間保留變數狀態。
您可以在 及其元素上 System.Collections.Generic.Stack<T> 執行三個主要作業:
的 Stack<T> 容量是 可以保留的項目 Stack<T> 數目。 當元素新增至 Stack<T>時,重新配置內部數位會自動增加容量。 您可以藉由呼叫 TrimExcess來減少容量。
如果 Count 小於堆疊的容量, Push 則 為 O (1) 作業。 如果需要增加容量以容納新元素, Push 會變成 O (n
) 作業,其中 n
是 Count。 Pop 是 O (1) 作業。
Stack<T> 接受 null
作為參考型別的有效值,並允許重複的專案。
建構函式
Stack<T>() |
初始化 Stack<T> 類別的新執行個體,這個執行個體為空白且具有預設的初始容量。 |
Stack<T>(IEnumerable<T>) |
初始化 Stack<T> 類別的新執行個體,其包含從指定之集合複製的項目,且具有容納複製之項目數目的足夠容量。 |
Stack<T>(Int32) |
初始化 Stack<T> 類別的新執行個體,其為空白且具有指定的初始容量或預設的初始容量 (兩者中較大的那一個)。 |
屬性
Capacity |
表示相同特定類型之執行個體的各種大小後進先出 (LIFO) 集合。 |
Count |
取得 Stack<T> 中所包含的項目數。 |
方法
Clear() |
從 Stack<T> 移除所有物件。 |
Contains(T) |
判斷某項目是否在 Stack<T> 中。 |
CopyTo(T[], Int32) | |
EnsureCapacity(Int32) |
確定此 Stack 的容量至少指定的 |
Equals(Object) |
判斷指定的物件是否等於目前的物件。 (繼承來源 Object) |
GetEnumerator() |
傳回 Stack<T> 的列舉值。 |
GetHashCode() |
做為預設雜湊函式。 (繼承來源 Object) |
GetType() |
取得目前執行個體的 Type。 (繼承來源 Object) |
MemberwiseClone() |
建立目前 Object 的淺層複製。 (繼承來源 Object) |
Peek() |
傳回 Stack<T> 頂端的物件而不需移除它。 |
Pop() |
移除並傳回在 Stack<T> 頂端的物件。 |
Push(T) |
將物件插入 Stack<T> 的頂端。 |
ToArray() |
複製 Stack<T> 至新陣列。 |
ToString() |
傳回代表目前物件的字串。 (繼承來源 Object) |
TrimExcess() |
如果該數目小於目前容量的 90%,則將容量設為 Stack<T> 中項目的實際數目。 |
TrimExcess(Int32) |
表示相同特定類型之執行個體的各種大小後進先出 (LIFO) 集合。 |
TryPeek(T) |
傳回值,其表示 Stack<T> 頂端是否存在物件;如果存在,則將該物件複製到 |
TryPop(T) |
傳回值,其表示 Stack<T> 頂端是否存在物件;如果存在,則將該物件複製到 |
明確介面實作
ICollection.CopyTo(Array, Int32) |
從特定的 ICollection 索引開始,將 Array 的項目複製到 Array。 |
ICollection.IsSynchronized |
取得值,這個值表示對 ICollection 的存取是否同步 (安全執行緒)。 |
ICollection.SyncRoot |
取得可用以同步存取 ICollection 的物件。 |
IEnumerable.GetEnumerator() |
傳回逐一查看集合的列舉值。 |
IEnumerable<T>.GetEnumerator() |
傳回逐一查看集合的列舉值。 |
擴充方法
適用於
執行緒安全性
Visual Basic 中的公用靜態 (Shared
) 此類型的成員是安全線程。 並非所有的執行個體成員都是安全執行緒。
Stack<T>可以同時支援多個讀取器,只要集合未修改即可。 即使如此,透過集合列舉本質上不是安全線程的程式。 若要確保列舉期間的執行緒安全性,您可以在整個列舉期間鎖定集合。 若要讓多重執行緒能夠存取集合以便進行讀取和寫入,您必須實作自己的同步處理。
另請參閱
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應