Why do we need iterators in c#?

前端 未结 10 1917
情话喂你
情话喂你 2021-02-05 18:35

Can somebody provide a real life example regarding use of iterators. I tried searching google but was not satisfied with the answers.

10条回答
  •  梦谈多话
    2021-02-05 19:19

    The canonical and simplest example is that it makes infinite sequences possible without the complexity of having to write the class to do that yourself:

    // generate every prime number
    public IEnumerator GetPrimeEnumerator()
    {
        yield return 2;
        var primes = new List();
        primesSoFar.Add(2);
        Func IsPrime = n => primes.TakeWhile(
            p => p <= (int)Math.Sqrt(n)).FirstOrDefault(p => n % p == 0) == 0;
    
        for (int i = 3; true; i += 2)
        {
            if (IsPrime(i))
            {
                yield return i;
                primes.Add(i);
            }
        }
    }
    

    Obviously this would not be truly infinite unless you used a BigInt instead of int but it gives you the idea. Writing this code (or similar) for each generated sequence would be tedious and error prone. the iterators do that for you. If the above example seems too complex for you consider:

    // generate every power of a number from start^0 to start^n
    public IEnumerator GetPowersEnumerator(int start)
    {   
        yield return 1; // anything ^0 is 1
        var x = start;
        while(true)
        {
            yield return x;
            x *= start;
        }      
    }
    

    They come at a cost though. Their lazy behaviour means you cannot spot common errors (null parameters and the like) until the generator is first consumed rather than created without writing wrapping functions to check first. The current implementation is also incredibly bad(1) if used recursively.

    Wiriting enumerations over complex structures like trees and object graphs is much easier to write as the state maintenance is largely done for you, you must simply write code to visit each item and not worry about getting back to it.


    1. I don't use this word lightly - a O(n) iteration can become O(N^2)

提交回复
热议问题