Stack<T>.GetEnumerator Método

Definición

Devuelve un enumerador para la colección Stack<T>.

public:
 System::Collections::Generic::Stack<T>::Enumerator GetEnumerator();
public System.Collections.Generic.Stack<T>.Enumerator GetEnumerator ();
member this.GetEnumerator : unit -> System.Collections.Generic.Stack<'T>.Enumerator
Public Function GetEnumerator () As Stack(Of T).Enumerator

Devoluciones

Estructura Stack<T>.Enumerator para la colección Stack<T>.

Ejemplos

En el ejemplo de código siguiente se muestra que la Stack<T> clase genérica es enumerable. La foreach instrucción (For Each en Visual Basic, for each en C++) se usa para enumerar la pila.

En el ejemplo de código se crea una pila de cadenas con capacidad predeterminada y se usa el Push método para insertar cinco cadenas en la pila. Los elementos de la pila se enumeran, lo que no cambia el estado de la pila. El Pop método se usa para quitar la primera cadena de la pila. El Peek método se usa para examinar el siguiente elemento de la pila y, a continuación, se usa el Pop método para desactivarlo.

El ToArray método se usa para crear una matriz y copiar los elementos de pila en ella y, a continuación, la matriz se pasa al Stack<T> constructor que toma IEnumerable<T>, creando una copia de la pila con el orden de los elementos invertidos. Se muestran los elementos de la copia.

Se crea una matriz dos veces el tamaño de la pila y el CopyTo método se usa para copiar los elementos de matriz a partir del centro de la matriz. El Stack<T> constructor se usa de nuevo para crear una copia de la pila con el orden de los elementos invertidos; por lo tanto, los tres elementos NULL están al final.

El Contains método se usa para mostrar que la cadena "cuatro" está en la primera copia de la pila, después de la cual el Clear método borra la copia y la Count propiedad muestra que la pila está vacía.

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

Comentarios

La foreach instrucción del lenguaje C# (for each en C++, For Each en Visual Basic) oculta la complejidad de los enumeradores. Por lo tanto, se recomienda el uso de foreach, en lugar de manipular directamente el enumerador.

Los enumeradores pueden usarse para leer los datos de la colección, pero no para modificar la colección subyacente.

En principio, el enumerador se coloca antes del primer elemento de la colección. En esta posición, el valor de propiedad Current está sin definir. Por lo tanto, debe llamar a MoveNext para adelantar el enumerador hasta el primer elemento de la colección antes de leer el valor de Current.

Current devuelve el mismo objeto hasta que se llama a MoveNext. MoveNext establece Current en el siguiente elemento.

Si MoveNext pasa el final de la colección, el enumerador se coloca después del último elemento de la colección y MoveNext devuelve false. Cuando el enumerador está en esta posición, las llamadas posteriores también devuelven MoveNextfalse. Si la última llamada a MoveNext se falsedevuelve , Current no está definida. No puede volver a establecer la propiedad Current en el primer elemento de la colección, sino que debe crear una nueva instancia del enumerador.

Un enumerador sigue siendo válido mientras la colección permanezca inalterada. Si se realizan cambios en la colección, como agregar, modificar o eliminar elementos, el enumerador se invalida irrecuperablemente y la siguiente llamada a MoveNext o IEnumerator.Reset inicia una InvalidOperationExceptionexcepción .

El enumerador no tiene acceso exclusivo a la colección y, por tanto, la enumeración en una colección no es intrínsicamente un procedimiento seguro para subprocesos. A fin de garantizar la seguridad de los subprocesos, se puede bloquear la colección durante toda la enumeración. Para permitir que varios subprocesos obtengan acceso de lectura y escritura a la colección, debe implementar su propia sincronización.

Las implementaciones predeterminadas de colecciones en System.Collections.Generic no se sincronizan.

Este método es una operación O(1).

Se aplica a

Consulte también