共用方式為


Stack<T>.GetEnumerator Method

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Returns an enumerator for the Stack<T>.

Namespace:  System.Collections.Generic
Assembly:  System (in System.dll)

Syntax

'Declaration
Public Function GetEnumerator As Stack<(Of <(<'T>)>)>..::..Enumerator
public Stack<(Of <(<'T>)>)>..::..Enumerator GetEnumerator()

Remarks

The foreach statement of the C# language (for each in C++, For Each in Visual Basic) hides the complexity of the enumerators. Therefore, using foreach is recommended, instead of directly manipulating the enumerator.

Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection.

Initially, the enumerator is positioned before the first element in the collection. At this position, Current is undefined. Therefore, you must call MoveNext to advance the enumerator to the first element of the collection before reading the value of Current.

Current returns the same object until MoveNext is called. MoveNext sets Current to the next element.

If MoveNext passes the end of the collection, the enumerator is positioned after the last element in the collection and MoveNext returns false. When the enumerator is at this position, subsequent calls to MoveNext also return false. If the last call to MoveNext returned false, Current is undefined. You cannot set Current to the first element of the collection again; you must create a new enumerator instance instead.

An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined.

The enumerator does not have exclusive access to the collection; therefore, 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.

Default implementations of collections in System.Collections.Generic are not synchronized.

This method is an O(1) operation.

Examples

The following code example demonstrates that the Stack<T> generic class is enumerable. The foreach statement (For Each in Visual Basic, for each in C++) is used to enumerate the queue.

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. The Pop method is used to pop the first string off the stack. The Peek method is used to look at the next item on the stack, and then the Pop method is used to pop it off.

The 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.

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

The 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.

Imports System.Collections.Generic

Module Example

   Public Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)

      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
         outputBlock.Text &= number & vbCrLf
      Next

      outputBlock.Text &= String.Format(vbLf & "Popping '{0}'", numbers.Pop()) & vbCrLf
      outputBlock.Text &= String.Format("Peek at next item to pop: {0}", _
          numbers.Peek()) & vbCrLf
      outputBlock.Text &= String.Format("Popping '{0}'", numbers.Pop()) & vbCrLf

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

      outputBlock.Text &= vbLf & "Contents of the first copy:" & vbCrLf
      For Each number As String In stack2
         outputBlock.Text &= number & vbCrLf
      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)

      outputBlock.Text &= String.Format(vbLf & _
          "Contents of the second copy, with duplicates and nulls:") & vbCrLf
      For Each number As String In stack3
         outputBlock.Text &= number & vbCrLf
      Next

      outputBlock.Text &= String.Format(vbLf & "stack2.Contains(""four"" & vbCrLf = {0}", _
          stack2.Contains("four"))

      outputBlock.Text &= vbLf & "stack2.Clear()" & vbCrLf
      stack2.Clear()
      outputBlock.Text &= String.Format(vbLf & "stack2.Count = {0}", _
          stack2.Count) & vbCrLf
   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
using System;
using System.Collections.Generic;

class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      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)
      {
         outputBlock.Text += number + "\n";
      }

      outputBlock.Text += String.Format("\nPopping '{0}'", numbers.Pop()) + "\n";
      outputBlock.Text += String.Format("Peek at next item to destack: {0}",
          numbers.Peek()) + "\n";
      outputBlock.Text += String.Format("Popping '{0}'", numbers.Pop()) + "\n";

      // 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());

      outputBlock.Text += "\nContents of the first copy:" + "\n";
      foreach (string number in stack2)
      {
         outputBlock.Text += number + "\n";
      }

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

      outputBlock.Text += String.Format("\nContents of the second copy, with duplicates and nulls:") + "\n";
      foreach (string number in stack3)
      {
         outputBlock.Text += number + "\n";
      }

      outputBlock.Text += String.Format("\nstack2.Contains(\"four\") = {0}",
          stack2.Contains("four")) + "\n";

      outputBlock.Text += "\nstack2.Clear()" + "\n";
      stack2.Clear();
      outputBlock.Text += String.Format("\nstack2.Count = {0}", stack2.Count) + "\n";
   }
}

/* 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
 */

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.