Array.GetEnumerator Método

Definição

Retorna e IEnumerator para o Array.

public:
 virtual System::Collections::IEnumerator ^ GetEnumerator();
public System.Collections.IEnumerator GetEnumerator();
public virtual System.Collections.IEnumerator GetEnumerator();
abstract member GetEnumerator : unit -> System.Collections.IEnumerator
override this.GetEnumerator : unit -> System.Collections.IEnumerator
Public Function GetEnumerator () As IEnumerator
Public Overridable Function GetEnumerator () As IEnumerator

Devoluções

E IEnumerator para o Array.

Implementações

Exemplos

O exemplo de código seguinte mostra como usar GetEnumerator para listar os elementos de um array.

using System;

public class SamplesArray  {

   public static void Main()  {

      // Creates and initializes a new Array.
      String[] myArr = new String[10];
      myArr[0] = "The";
      myArr[1] = "quick";
      myArr[2] = "brown";
      myArr[3] = "fox";
      myArr[4] = "jumps";
      myArr[5] = "over";
      myArr[6] = "the";
      myArr[7] = "lazy";
      myArr[8] = "dog";

      // Displays the values of the Array.
      int i = 0;
      System.Collections.IEnumerator myEnumerator = myArr.GetEnumerator();
      Console.WriteLine( "The Array contains the following values:" );
      while (( myEnumerator.MoveNext() ) && ( myEnumerator.Current != null ))
         Console.WriteLine( "[{0}] {1}", i++, myEnumerator.Current );
   }
}


/*
This code produces the following output.

The Array contains the following values:
[0] The
[1] quick
[2] brown
[3] fox
[4] jumps
[5] over
[6] the
[7] lazy
[8] dog

*/
// Creates and initializes a new Array.
let myArr = Array.zeroCreate 10
myArr[0..8] <- 
   [| "The"
      "quick"
      "brown"
      "fox"
      "jumps"
      "over"
      "the"
      "lazy"
      "dog" |]

// Displays the values of the Array.
let mutable i = 0
let myEnumerator = myArr.GetEnumerator()
printfn "The Array contains the following values:"

while myEnumerator.MoveNext() && myEnumerator.Current <> null do
      printfn $"[{i}] {myEnumerator.Current}" 
      i <- i + 1


// This code produces the following output.
//     The Array contains the following values:
//     [0] The
//     [1] quick
//     [2] brown
//     [3] fox
//     [4] jumps
//     [5] over
//     [6] the
//     [7] lazy
//     [8] dog
Public Class SamplesArray

   Public Shared Sub Main()

      ' Creates and initializes a new Array.
      Dim myArr(10) As [String]
      myArr(0) = "The"
      myArr(1) = "quick"
      myArr(2) = "brown"
      myArr(3) = "fox"
      myArr(4) = "jumps"
      myArr(5) = "over"
      myArr(6) = "the"
      myArr(7) = "lazy"
      myArr(8) = "dog"

      ' Displays the values of the Array.
      Dim i As Integer = 0
      Dim myEnumerator As System.Collections.IEnumerator = myArr.GetEnumerator()
      Console.WriteLine("The Array contains the following values:")
      While myEnumerator.MoveNext() And Not (myEnumerator.Current Is Nothing)
         Console.WriteLine("[{0}] {1}", i, myEnumerator.Current)
         i += 1
      End While 

   End Sub

End Class


'This code produces the following output.
'
'The Array contains the following values:
'[0] The
'[1] quick
'[2] brown
'[3] fox
'[4] jumps
'[5] over
'[6] the
'[7] lazy
'[8] dog

Observações

A instrução foreach da linguagem C# (For Each em Visual Basic) esconde a complexidade dos enumeradores. Por isso, recomenda-se o uso foreach , em vez de manipular diretamente o enumerador.

Os enumeradores podem ser usados para ler os dados da coleção, mas não podem ser usados para modificar a coleção subjacente.

Inicialmente, o enumerador é posicionado antes do primeiro elemento da coleção. Reset também traz o recenseador de volta a esta posição. Nesta posição, Current é indefinido. Portanto, deve chamar MoveNext para avançar o enumerador até ao primeiro elemento da coleção antes de ler o valor de Current.

Current devolve o mesmo objeto até que qualquer MoveNext ou Reset seja chamado. MoveNext passa Current para o elemento seguinte.

Se MoveNext passar o final da coleção, o enumerador é posicionado após o último elemento da coleção e MoveNext retorna false. Quando o enumerador está nesta posição, chamadas subsequentes também MoveNext retornam false. Se a última chamada devolvida MoveNextfalse, Current for indefinida. Para definir Current novamente para o primeiro elemento da coleção, pode chamar Reset seguido de MoveNext.

Um enumerador mantém-se válido enquanto a coleção permanecer inalterada. Se forem feitas alterações à coleção, como adicionar, modificar ou eliminar elementos, o enumerador fica irremediavelmente invalidado e o seu comportamento é indefinido.

O enumerador não tem acesso exclusivo à coleção; Portanto, enumerar através de uma coleção não é, intrinsecamente, um procedimento seguro para threads. Para garantir a segurança da linha durante a enumeração, pode bloquear a coleção durante toda a enumeração. Para permitir que a coleção seja acedida por múltiplos threads para leitura e escrita, deve implementar a sua própria sincronização.

Este método é uma operação O(1).

Aplica-se a