Stack<T> 类

定义

表示相同指定类型的实例可变大小的后进先出 (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>泛型类的几个方法。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.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> 类的新实例,该实例为空并且具有默认初始容量。Initializes a new instance of the Stack<T> class that is empty and has the default initial capacity.

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> 类的新实例,该实例为空并且具有指定的初始容量或默认初始容量(这两个容量中的较大者)。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

获取 Stack<T> 中包含的元素数。Gets the number of elements contained in the Stack<T>.

方法

Clear()

Stack<T> 中移除所有对象。Removes all objects from the Stack<T>.

Contains(T)

确定某元素是否在 Stack<T> 中。Determines whether an element is in the Stack<T>.

CopyTo(T[], Int32)

从指定数组索引开始将 Stack<T> 复制到现有一维 Array 中。Copies the Stack<T> to an existing one-dimensional Array, starting at the specified array index.

Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
GetEnumerator()

返回 Stack<T> 的一个枚举数。Returns an enumerator for the Stack<T>.

GetHashCode()

用作默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
Peek()

返回位于 Stack<T> 顶部的对象但不将其移除。Returns the object at the top of the Stack<T> without removing it.

Pop()

移除并返回位于 Stack<T> 顶部的对象。Removes and returns the object at the top of the Stack<T>.

Push(T)

将对象插入 Stack<T> 的顶部。Inserts an object at the top of the Stack<T>.

ToArray()

Stack<T> 复制到新数组中。Copies the Stack<T> to a new array.

ToString()

返回一个表示当前对象的 string。Returns a string that represents the current object.

(继承自 Object)
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)
TryPop(T)

显式界面实现

ICollection.CopyTo(Array, Int32)

从特定的 ICollection 索引开始,将 Array 的元素复制到一个 Array 中。Copies the elements of the ICollection to an Array, starting at a particular Array index.

ICollection.IsSynchronized

获取一个值,该值指示是否同步对 ICollection 的访问(线程安全)。Gets a value indicating whether access to the ICollection is synchronized (thread safe).

ICollection.SyncRoot

获取可用于同步对 ICollection 的访问的对象。Gets an object that can be used to synchronize access to the ICollection.

IEnumerable.GetEnumerator()

返回循环访问集合的枚举数。Returns an enumerator that iterates through a collection.

IEnumerable<T>.GetEnumerator()

返回一个循环访问集合的枚举器。Returns an enumerator that iterates through the collection.

扩展方法

CopyToDataTable<T>(IEnumerable<T>)

在给定其泛型参数 TDataTable 的输入 DataRow 对象的情况下,返回包含 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)

在给定其泛型参数 TDataRow 的输入 DataTable 对象的情况下,将 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)

在给定其泛型参数 TDataRow 的输入 DataTable 对象的情况下,将 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)

IEnumerable 的元素强制转换为指定的类型。Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable)

根据指定类型筛选 IEnumerable 的元素。Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable)

启用查询的并行化。Enables parallelization of a query.

AsQueryable(IEnumerable)

IEnumerable 转换为 IQueryableConverts an IEnumerable to an IQueryable.

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)

返回经过筛选的元素集合,其中包含源集合中每个节点的上级。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>)

返回源集合中每个文档和元素的子代节点的集合。Returns a collection of the descendant nodes of every document and element in the source collection.

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)

返回经过筛选的元素集合,其中包含源集合中每个元素和文档的子代元素。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>)

返回源集合中每个元素和文档的子元素的集合。Returns a collection of the child elements of every element and document in the source collection.

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

返回节点集合(其中包含源集合中的所有节点),并按文档顺序排列。Returns a collection of nodes that contains all nodes in the source collection, sorted in document order.

Nodes<T>(IEnumerable<T>)

返回源集合中每个文档和元素的子节点集合。Returns a collection of the child nodes of every document and element in the source collection.

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.

另请参阅