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
[<System.Runtime.InteropServices.ComVisible(false)>]
[<System.Serializable>]
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)
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>main操作:
的 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> 类的新实例,该实例为空并且具有指定的初始容量或默认初始容量(这两个容量中的较大者)。 |
属性
Count |
获取 Stack<T> 中包含的元素数。 |
方法
Clear() |
从 Stack<T> 中移除所有对象。 |
Contains(T) |
确定某元素是否在 Stack<T> 中。 |
CopyTo(T[], Int32) | |
EnsureCapacity(Int32) |
确保此堆栈的容量至少为指定的 |
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> 中的实际元素数。 |
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>只要集合未修改,就可以同时支持多个读取器。 即便如此,通过集合枚举本质上也不是线程安全的过程。 若要确保枚举过程中的线程安全性,可以在整个枚举过程中锁定集合。 若要允许多个线程访问集合以进行读写操作,则必须实现自己的同步。