Why do we need iterators in c#?

前端 未结 10 2072
情话喂你
情话喂你 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:10

    Simple example : a function that generates a sequence of integers :

    static IEnumerable GetSequence(int fromValue, int toValue)
    {
        if (toValue >= fromValue)
        {
            for (int i = fromValue; i <= toValue; i++)
            {
                yield return i;
            }
        }
        else
        {
            for (int i = fromValue; i >= toValue; i--)
            {
                yield return i;
            }
        }
    }
    

    To do it without an iterator, you would need to create an array then enumerate it...

提交回复
热议问题