IEnumerable Interfejs

Definicja

Uwidacznia moduł wyliczający, który obsługuje prostą iterację w kolekcji innej niż ogólna.

C#
public interface IEnumerable
C#
[System.Runtime.InteropServices.Guid("496B0ABE-CDEE-11d3-88E8-00902754C43A")]
public interface IEnumerable
C#
[System.Runtime.InteropServices.Guid("496B0ABE-CDEE-11d3-88E8-00902754C43A")]
[System.Runtime.InteropServices.ComVisible(true)]
public interface IEnumerable
Pochodne
Atrybuty

Przykłady

W poniższym przykładzie kodu przedstawiono najlepsze rozwiązanie dotyczące iterowania kolekcji niestandardowej przez zaimplementowanie interfejsów IEnumerable i IEnumerator. W tym przykładzie elementy członkowskie tych interfejsów nie są jawnie wywoływane, ale są implementowane w celu obsługi korzystania z foreach (For Each w Visual Basic) w celu iteracji w kolekcji. Ten przykład to kompletna aplikacja konsolowa. Aby skompilować aplikację języka Visual Basic, zmień obiektu uruchamiania na Główne na stronie właściwości projektu.

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

Uwagi

IEnumerable jest interfejsem podstawowym dla wszystkich kolekcji innych niż ogólne, które można wyliczyć. Aby uzyskać ogólną wersję tego interfejsu, zobacz System.Collections.Generic.IEnumerable<T>. IEnumerable zawiera jedną metodę GetEnumerator, która zwraca IEnumerator. IEnumerator umożliwia iterowanie kolekcji przez uwidacznianie właściwości Current oraz metod MoveNext i Reset.

Najlepszym rozwiązaniem jest zaimplementowanie IEnumerable i IEnumerator w klasach kolekcji w celu włączenia składni foreach (For Each w języku Visual Basic), jednak implementacja IEnumerable nie jest wymagana. Jeśli kolekcja nie implementuje IEnumerable, należy nadal postępować zgodnie ze wzorcem iteratora, aby obsługiwać tę składnię, podając metodę GetEnumerator zwracającą interfejs, klasę lub strukturę. W przypadku korzystania z języka Visual Basic należy podać implementację IEnumerator, która jest zwracana przez GetEnumerator. Podczas opracowywania za pomocą języka C# należy podać klasę zawierającą właściwość Current oraz metody MoveNext i Reset zgodnie z opisem w IEnumerator, ale klasa nie musi implementować IEnumerator.

Metody

GetEnumerator()

Zwraca moduł wyliczający, który iteruje za pośrednictwem kolekcji.

Metody rozszerzania

Cast<TResult>(IEnumerable)

Rzutuje elementy IEnumerable do określonego typu.

OfType<TResult>(IEnumerable)

Filtruje elementy IEnumerable na podstawie określonego typu.

AsParallel(IEnumerable)

Umożliwia równoległość zapytania.

AsQueryable(IEnumerable)

Konwertuje IEnumerable na IQueryable.

Dotyczy

Produkt Wersje
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

Zobacz też