Distinction between iterator and enumerator

后端 未结 9 608
南旧
南旧 2020-12-07 08:47

An interview question for a .NET 3.5 job is \"What is the difference between an iterator and an enumerator\"?

This is a core distinction to make, what with LINQ, etc

9条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-07 08:49

    Since no examples were given, here is one that was helpful to me.

    An enumerator is an object that you get when you call .GetEnumerator() on a class or type that implements the IEnumerator interface. When this interface is implemented, you have created all the code necessary for the compilor to enable you to use foreach to "iterate" over your collection.

    Don't get that word 'iterate" confused with iterator though. Both the Enumerator and the iterator allow you to "iterate". Enumerating and iterating are basically the same process, but are implemented differently. Enumerating means you've impleneted the IEnumerator interface. Iterating means you've created the iterator construct in your class (demonstrated below), and you are calling foreach on your class, at which time the compilor automatically creates the enumerator functionality for you.

    Also note that you don't have to do squat with your enumerator. You can call MyClass.GetEnumerator() all day long, and do nothing with it (example:

    IEnumerator myEnumeratorThatIWillDoNothingWith = MyClass.GetEnumerator()).

    Note too that your iterator construct in your class only realy gets used when you are actually using it, i.e. you've called foreach on your class.

    Here is an iterator example from msdn:

    public class DaysOfTheWeek : System.Collections.IEnumerable
    {
    
         string[] days = { "Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat" };
    
         //This is the iterator!!!
         public System.Collections.IEnumerator GetEnumerator()
         {
             for (int i = 0; i < days.Length; i++)
             {
                 yield return days[i];
             }
         }
    
    }
    
    class TestDaysOfTheWeek
    {
        static void Main()
        {
            // Create an instance of the collection class
            DaysOfTheWeek week = new DaysOfTheWeek();
    
            // Iterate with foreach - this is using the iterator!!! When the compiler
            //detects your iterator, it will automatically generate the Current, 
            //MoveNext and Dispose methods of the IEnumerator or IEnumerator interface
            foreach (string day in week)
            {
                System.Console.Write(day + " ");
            }
        }
    }
    // Output: Sun Mon Tue Wed Thr Fri Sat
    

提交回复
热议问题