When should I use IEnumerable and GetEnumerator?

In many of our projects, I saw several custom collections / container classes that contain some kind of common collection, for example. a List(of T).

Typically, they have a GetXXX method that returns an IEnumerable of any type that uses a custom collection class, so the internal collection can be iterated using a foreach loop.

eg.

public IEnumerable<UploadState> GetStates
{
    get
    {
        return new List<UploadState>(m_states);
    }
}

My question is whether these classes should instead implement an interface IEnumerableand call GetEnumeratorin the List itself.

Is there a preferred way, or does it depend on the developer?

+5
source share
6 answers

, , IEnumerable<T>. . :

public class People : IEnumerable<Person>
{
    List<Person> persons = new List<Person>();

    public IEnumerator<Person> GetEnumerator()
    {
        return persons.GetEnumerator();
    }
}

, IEnumerable :

public class Flight
{
    List<Person> passengers = new List<Person>();

    public IEnumerable<Person> Passengers
    {
        get { return passengers; }
    }
}

.

+2

:

public IEnumerable<UploadState> GetStates
{
    get
    {
        foreach (var state in m_states) { 
            yield return state; 
        }
    }
}

, , ( List<T>), List<T>.

. . , , IEnumerable<T>.

+2

, . , m_states, , . , Add/Remove/Update . .

m_states , new, // ( !), .

IEnumerable<T>, generic, List<T>.

+1

System.Collections.ObjectModel. IEnumerable<T> IEnumerable.

0

, , , . - , , ; IEnumerable. , .

0

All Articles