协程(四)yield与迭代器

2019-10-28  本文已影响0人  86a262e62b0b

协程(一)基本使用
协程(二)协程什么时候调用
协程(三)IEnumerable、IEnumerator、foreach、迭代
协程(四)yield与迭代器
协程(五)简单模拟协程
协程(六)有关优化

yield文档:
https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/yield

一.yield

yield语句两种形式:

yield return <expression>;
yield break;

二. 迭代器方法

  1. 迭代器的声明必须满足以下要求:
  1. 提示:

代码实现:

IEnumerable<string> elements = MyIteratorMethod();
foreach (string element in elements)
{
   ...
}
理解:

另外一个案例:

public class PowersOf2
{
    static void Main()
    {
        // Display powers of 2 up to the exponent of 8:
        foreach (int i in Power(2, 8))
        {
            Console.Write("{0} ", i);
        }
    }

    public static System.Collections.Generic.IEnumerable<int> Power(int number, int exponent)
    {
        int result = 1;

        for (int i = 0; i < exponent; i++)
        {
            result = result * number;
            yield return result;
        }
    }

    // Output: 2 4 8 16 32 64 128 256
}

三. 下面的示例演示一个作为迭代器的 get 访问器

public static void ShowGalaxies()
{
    var theGalaxies = new Galaxies();
    foreach (Galaxy theGalaxy in theGalaxies.NextGalaxy)
    {
        Debug.WriteLine(theGalaxy.Name + " " + theGalaxy.MegaLightYears.ToString());
    }
}

public class Galaxies
{

    public System.Collections.Generic.IEnumerable<Galaxy> NextGalaxy
    {
        get
        {
            yield return new Galaxy { Name = "Tadpole", MegaLightYears = 400 };
            yield return new Galaxy { Name = "Pinwheel", MegaLightYears = 25 };
            yield return new Galaxy { Name = "Milky Way", MegaLightYears = 0 };
            yield return new Galaxy { Name = "Andromeda", MegaLightYears = 3 };
        }
    }
}

public class Galaxy
{
    public String Name { get; set; }
    public int MegaLightYears { get; set; }
}
上一篇 下一篇

猜你喜欢

热点阅读