[编程基础][C#]yield

yield语法糖是对一种复杂行为的简化,将一段代码简化为一种简单的形式。

 

案例一

public static void Main()
{
    foreach (var i in Fibonacci().Take(20))
    {
        Console.WriteLine(i);
    }

    Console.WriteLine("Hello World!");
}

private static IEnumerable<int> Fibonacci()
{
    int current = 1, next = 1;

    while (true)
    {
        yield return current;
        next = current + (current = next);
    }
}

运算结果:

 

案例二

static void Main(string[] args)
{

    foreach (int i in Power(2, 8, ""))
    {
        Console.Write("{0} ", i);
    }
    Console.ReadKey();
}


public static IEnumerable<int> Power(int number, int exponent, string s)
{
    int result = 1;

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

运算结果: 2 4 8 16 32 64 128 256 3 4 5

 

一般思路为

public static IEnumerable<int> Power(int number, int exponent, string s)
{
    int result = 1;
    //接口不能实例化,我们这儿new一个实现了IEnumerable接口的List
    IEnumerable<int> example = new List<int>();
    for (int i = 0; i < exponent; i++)
    {
        result = result * number;
        (example as List<int>).Add(result);
    }
    return example;
}

IEnumerable是一个常用的返回类型。每次使用都要new一个List,或者其他实现了该接口的类型。与其使用其他类型,不如自己定制一个实现了IEnumerable接口专门用来返回IEnumerable类型的类型。微软帮我们定制好了,就是yield关键字这个语法糖。

 

 

yield注意事项:

 

不能在具有以下特点的方法中包含 yield return 或 yield break 语句:
  匿名方法。 有关详细信息,请参阅匿名方法(C# 编程指南)。
  包含不安全(unsafe)的块的方法。 有关详细信息,请参阅unsafe(C# 参考)。


异常处理

  不能将 yield return 语句置于 try-catch 块中。 可将 yield return 语句置于 try-finally 语句的 try 块中。

  yield break 语句可以位于 try 块或 catch 块,但不能位于 finally 块。

  如果 foreach 主体(在迭代器方法之外)引发异常,则将执行迭代器方法中的 finally 块。

 

 

参考

https://www.cnblogs.com/santian/p/4389675.html

posted @ 2021-02-27 18:17  mwy9  阅读(169)  评论(0编辑  收藏  举报