C# 迭代器

方法一

可以通过申明一个迭代器的属性实现迭代器
方法是
<访问控制符> IEnumerable <T> 迭代器名称
每次访问迭代器,会从老地方进入迭代器函数,然后迭代器 yield 或终止,下次再从 yield 的下一行开始执行。
如果迭代器函数已经结束,不需要返回任何东西,foreach 会结束对其的访问。



using System.Text;

namespace ConsoleApp1
{
    class Class2
    {
        static void Main()
        {
            foreach (string word in WordSequence("  @Fuck,you, leatherman!"))
            {
                Console.WriteLine(word);
            }
            Console.ReadKey();
        }

        public static IEnumerable<string> WordSequence(string str)
        {
            StringBuilder newWord = new StringBuilder(20);
            int status = 0;
            for (int i = 0; i < str.Length; i++)
            {
                if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) {
                    status = 1;
                    newWord.Append(str[i]);
                }
                else if (status == 1)
                {
                    yield return newWord.ToString();
                    newWord.Clear();
                    status = 0;
                }
            }
            if (newWord.Length > 0)
            {
                yield return newWord.ToString();
            }
        } 
    } 
}

Outputs:

Fuck
you
leather
man

附:
1. C# 有和 Java 类似的 StringBuilder
2. string 的字符通过 str[i] 下标访问。

方法2

实现IEnumerable接口,需要实现GetEmumerator方法

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];  
        }  
    }  
}  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值