Stack Stack Stack Stack Class

定义

表示对象的简单后进先出 (LIFO) 非泛型集合。Represents a simple last-in-first-out (LIFO) non-generic collection of objects.

public ref class Stack : ICloneable, System::Collections::ICollection
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public class Stack : ICloneable, System.Collections.ICollection
type Stack = class
    interface ICollection
    interface ICloneable
    interface IEnumerable
Public Class Stack
Implements ICloneable, ICollection
继承
StackStackStackStack
属性
实现

示例

下面的示例演示如何创建值并将其添加到堆栈中,以及如何显示其值。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 );
   }

   Console::WriteLine();
}

/* 
 This code produces the following output.
 
 myStack
     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();
      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 );
   }

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

}


/* 
This code produces the following output.

myStack
    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()
        myStack.Push("Hello")
        myStack.Push("World")
        myStack.Push("!")
        
        ' Displays the properties and values of the Stack.
        Console.WriteLine("myStack")
        Console.WriteLine(ControlChars.Tab & "Count:    {0}", myStack.Count)
        Console.Write(ControlChars.Tab & "Values:")
        PrintValues(myStack)
    End Sub
    
    Public Shared Sub PrintValues(myCollection As IEnumerable)
        Dim obj As [Object]
        For Each obj In  myCollection
            Console.Write("    {0}", obj)
        Next obj
        Console.WriteLine()
    End Sub

End Class

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

注解

@No__t 的容量为 Stack 可以容纳的元素数。The capacity of a Stack is the number of elements the Stack can hold. 向 @no__t 添加元素时,会根据需要通过重新分配自动增加容量。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 是 @no__t 操作。If Count is less than the capacity of the stack, Push is an O(1) operation. 如果需要增加容量以容纳新元素,Push 会成为 @no__t 操作,其中 nCountIf the capacity needs to be increased to accommodate the new element, Push becomes an O(n) operation, where n is Count. @no__t 为 O(1) 操作。Pop is an O(1) operation.

Stack 接受 @no__t 为有效值,并允许重复元素。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 复制到现有一维 Array 中。Copies 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 的浅表副本。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.

适用于

线程安全性

此类型的公共静态(@no__t 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.

若要保证 @no__t 的线程安全,必须通过 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.

另请参阅