what is IEnumerable in .net

后端 未结 5 1086
既然无缘
既然无缘 2020-12-02 08:47

what is IEnumerable in .net?

5条回答
  •  旧巷少年郎
    2020-12-02 09:41

    It's an interface implemented by Collection types in .NET that provide the Iterator pattern. There also the generic version which is IEnumerable.

    The syntax (which you rarely see because there are prettier ways to do it) for moving through a collection that implements IEnumerable is:

    IEnumerator enumerator = collection.GetEnumerator();
    
    while(enumerator.MoveNext())
    {
        object obj = enumerator.Current;
        // work with the object
    }
    

    Which is functionaly equivalent to:

    foreach(object obj in collection)
    {
        // work with the object
    }
    

    If the collection supports indexers, you could also iterate over it with the classic for loop method but the Iterator pattern provides some nice extras like the ability to add synchronization for threading.

提交回复
热议问题