简体   繁体   English

有谁知道为什么这个程序的输出是这样的?(在c#中使用迭代器)

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

using System;
using System.Collections;
namespace 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”,

mon

What will be the reason? 会是什么原因?

This is happening because there's no loop in your getdays method. 发生这种情况是因为getdays方法中没有循环。 You just yield once, returning the first item - "mon" - and that's it! 你只需yield一次,返回第一项 - “星期一” - 就是这样!

Here's an easy fix. 这是一个简单的解决方案。 (If possible, change the IEnumerable return type to IEnumerable<string> too.) (如果可能,将IEnumerable返回类型更改为IEnumerable<string> 。)

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

You need to have a loop around the yield return : 你需要围绕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) 作为一种替代方法,因为你的getdays似乎是只读的,并没有特别做其他事情(从你的例子)

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);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM