开发者

Anybody know why the Output of this program is like this?(using iterator in c#)

using System;
using System.Collections;
namesp开发者_如何学JAVAace Iterator_test
{
 class Day
 {
    int days_idx = -1;
    private String[] days = { "mon", "tue", "wed","thu","fri","sat","sun" };
    public IEnumerable getdays()
    {
        days_idx++;
        yield return days[days_idx];
    }
 }
 class Program
 {
    static void Main(string[] args)
    {
        Day d = new Day();
        foreach (string day in d.getdays())
        {
            Console.WriteLine(day);
        }
    }
  }
}

Actually the output should be,

mon
tue
wed
thu
fri
sat 
sun

but its printing only "mon" as,

mon

What will be the reason?


This is happening because there's no loop in your getdays method. You just yield once, returning the first item - "mon" - and that's it!

Here's an easy fix. (If possible, change the IEnumerable return type to IEnumerable<string> too.)

public IEnumerable getdays()
{
    foreach (string day in days)
    {
        yield return day;
    }
}


You need to have a loop around the yield return:

public IEnumerable getdays()
{    
    while (days_idx < 6)
    {
        days_idx++;
        yield return days[days_idx];
    }    
}


Luke and Gonzalo are correct.

as an alternate approach as your getdays seems to be readonly and doesn't particularly do much else (from your example)

class Day
{
    public IEnumerable days
    {
        get
        {
            return new string[] { "mon", "tue", "wed", "thu", "fri", "sat", "sun" };
        }
    }

}
class Program
{
    static void Main(string[] args)
    {
        Day d = new Day();
        foreach (string day in d.days)
        {
            Console.WriteLine(day);
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜