Cet article a fait l’objet d’une traduction automatique. Pour afficher l’article en anglais, activez la case d’option Anglais. Vous pouvez également afficher le texte anglais dans une fenêtre contextuelle en faisant glisser le pointeur de la souris sur le texte traduit.
Traduction
Anglais

IEnumerator interface

 

Date de publication : novembre 2016

Prend en charge une itération simple sur une collection non générique.

Espace de noms:   System.Collections
Assembly:  mscorlib (dans mscorlib.dll)

[GuidAttribute("496B0ABF-CDEE-11d3-88E8-00902754C43A")]
[ComVisibleAttribute(true)]
public interface IEnumerator

NomDescription
System_CAPS_pubpropertyCurrent

Obtient l’élément actuel dans la collection.

NomDescription
System_CAPS_pubmethodMoveNext()

Avance l’énumérateur à l’élément suivant de la collection.

System_CAPS_pubmethodReset()

Rétablit l’énumérateur à sa position initiale, qui précède le premier élément de la collection.

IEnumerator is the base interface for all non-generic enumerators.

For the generic version of this interface see T:System.Collections.Generic.IEnumerator`1.

The foreach statement of the C# language (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.

The M:System.Collections.IEnumerator.Reset method is provided for COM interoperability and does not need to be fully implemented; instead, the implementer can throw a T:System.NotSupportedException.

Initially, the enumerator is positioned before the first element in the collection. You must call the M:System.Collections.IEnumerator.MoveNext method to advance the enumerator to the first element of the collection before reading the value of P:System.Collections.IEnumerator.Current; otherwise, P:System.Collections.IEnumerator.Current is undefined.

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

If M:System.Collections.IEnumerator.MoveNext passes the end of the collection, the enumerator is positioned after the last element in the collection and M:System.Collections.IEnumerator.MoveNext returns false. When the enumerator is at this position, subsequent calls to M:System.Collections.IEnumerator.MoveNext also return false. If the last call to M:System.Collections.IEnumerator.MoveNext returned false, calling P:System.Collections.IEnumerator.Current throws an exception.

To set P:System.Collections.IEnumerator.Current to the first element of the collection again, you can call M:System.Collections.IEnumerator.Reset, if it’s implemented, followed by M:System.Collections.IEnumerator.MoveNext. If M:System.Collections.IEnumerator.Reset is not implemented, you must create a new enumerator instance to return to the first element of the collection.

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 the next call to M:System.Collections.IEnumerator.MoveNext or M:System.Collections.IEnumerator.Reset throws an T:System.InvalidOperationException. If the collection is modified between M:System.Collections.IEnumerator.MoveNext and P:System.Collections.IEnumerator.Current, P:System.Collections.IEnumerator.Current returns the element that it is set to, even if the enumerator is already invalidated.

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

The following code example demonstrates the implementation of the T:System.Collections.IEnumerable and T:System.Collections.IEnumerator interfaces for a custom collection. In this example, members of these interfaces are not explicitly called, but they are implemented to support the use of foreach (for each in Visual Basic) to iterate through the collection.

using System;
using System.Collections;

// Simple business object.
public class Person
{
    public Person(string fName, string lName)
    {
        this.firstName = fName;
        this.lastName = lName;
    }

    public string firstName;
    public string lastName;
}

// Collection of Person objects. This class
// implements IEnumerable so that it can be used
// with ForEach syntax.
public class People : IEnumerable
{
    private Person[] _people;
    public People(Person[] pArray)
    {
        _people = new Person[pArray.Length];

        for (int i = 0; i < pArray.Length; i++)
        {
            _people[i] = pArray[i];
        }
    }

// Implementation for the GetEnumerator method.
    IEnumerator IEnumerable.GetEnumerator()
    {
       return (IEnumerator) GetEnumerator();
    }

    public PeopleEnum GetEnumerator()
    {
        return new PeopleEnum(_people);
    }
}

// When you implement IEnumerable, you must also implement IEnumerator.
public class PeopleEnum : IEnumerator
{
    public Person[] _people;

    // Enumerators are positioned before the first element
    // until the first MoveNext() call.
    int position = -1;

    public PeopleEnum(Person[] list)
    {
        _people = list;
    }

    public bool MoveNext()
    {
        position++;
        return (position < _people.Length);
    }

    public void Reset()
    {
        position = -1;
    }

    object IEnumerator.Current
    {
        get
        {
            return Current;
        }
    }

    public Person Current
    {
        get
        {
            try
            {
                return _people[position];
            }
            catch (IndexOutOfRangeException)
            {
                throw new InvalidOperationException();
            }
        }
    }
}

class App
{
    static void Main()
    {
        Person[] peopleArray = new Person[3]
        {
            new Person("John", "Smith"),
            new Person("Jim", "Johnson"),
            new Person("Sue", "Rabon"),
        };

        People peopleList = new People(peopleArray);
        foreach (Person p in peopleList)
            Console.WriteLine(p.firstName + " " + p.lastName);

    }
}

/* This code produces output similar to the following:
 *
 * John Smith
 * Jim Johnson
 * Sue Rabon
 *
 */

Plateforme Windows universelle
Disponible depuis 8
.NET Framework
Disponible depuis 1.1
Bibliothèque de classes portable
Pris en charge dans : plateformes .NET portables
Silverlight
Disponible depuis 2.0
Silverlight pour Windows Phone
Disponible depuis 7.0
Windows Phone
Disponible depuis 8.1
Retour au début
Afficher: