yield return 关键字的详解

来源:互联网 发布:淘宝图片护盾从哪进? 编辑:程序博客网 时间:2024/06/05 23:03

http://2sws.blog.163.com/blog/static/179102492009843454582/

 

/// <summary>
/// yield return 关键字的详解
/// 下面的例子可以进行正常的迭带运算,想要理解运行的机制的
/// 话,我们可以使用F11键进行单步运行,就可以看明白了。
/// </summary>

public class Persons : System.Collections.IEnumerable
{
    #region IEnumerable 成员

    public System.Collections.IEnumerator GetEnumerator()
    {
        yield return "1";
        yield return "2";
        yield return "3";
        yield return "4";
        yield return "5";
        yield return "6";
    }

    #endregion
}

class program
{
    static void Main()
    {
        Persons arrPersons = new Persons();
        foreach (string s in arrPersons)
        {
            System.Console.WriteLine(s);
        }

        System.Console.ReadLine();
    }
}