C#迭代器的使用

原文地址:http://msdn.microsoft.com/zh-cn/library/65zzykke.aspx 
 

创建迭代器最常用的方法是对 IEnumerable 接口实现 GetEnumerator 方法,例如:

public System.Collections.IEnumerator GetEnumerator()
{
    for (int i = 0; i < 10; i++)
    {
        yield return i;
    }
}

GetEnumerator 方法的存在使得类型成为可枚举的类型,并允许使用 foreach 语句。 如果上面的方法是 ListClass 的类定义的一部分,则可以对该类使用 foreach,如下所示:


static void Main()
{
    ListClass listClass1 = new ListClass();

    foreach (int i in listClass1)
    {
        System.Console.Write(i + " ");
    }
    // Output: 0 1 2 3 4 5 6 7 8 9
}

posted @ 2012-05-22 12:45  ゞ追忆o0ゞ  阅读(165)  评论(0编辑  收藏  举报