IEnumerator在C#中的工作 [英] Working of IEnumerator in c#

查看:130
本文介绍了IEnumerator在C#中的工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

static void Main()
{
    DaysOfTheWeek days = new DaysOfTheWeek();

    foreach (string day in days)
    {
        Console.Write(day + " ");
    }

    // Output: Sun Mon Tue Wed Thu Fri Sat  
    Console.ReadKey();
}

public class DaysOfTheWeek : IEnumerable
{
    private string[] days = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

    public IEnumerator GetEnumerator()
    {
        for (int index = 0; index < days.Length; index++)
        {
            // Yield each day of the week.  
            yield return days[index];
        }
    }
}

在foreach循环中会发生什么.它是否为每次迭代都调用GetEnumerator函数,或者foreach被GetEnumerator函数替代?在这种情况下,复杂度是否为O(n2)?

What happens in the foreach loop. Does it calls the GetEnumerator function, for every iteration or the foreach is replaced by the GetEnumerator function? Does the complexity goes to O(n2) in this case?

推荐答案

此博客文章中对yield return的描述很不错:

There is a nice desription of yield return in this blog post:

https://www.kenneth- truyers.net/2016/05/12/yield-return-in-c/

基本上是说

foreach循环的每次迭代都调用iterator方法.当达到yield return语句时,将返回值,并保留代码中的当前位置.下次调用迭代器函数时,将从该位置重新开始执行.

Each iteration of the foreach loop calls the iterator method. When the yield return statement is reached the value is returned, and the current location in code is retained. Execution is restarted from that location the next time that the iterator function is called.

由于保留了下一个通话的位置,我认为复杂度应为O(n)而不是O(n2).

As the location is retained for the next call, I think complexity should be O(n) rather than O(n2).

这篇关于IEnumerator在C#中的工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆