C#中YieldReturn的用法

时间:2024-11-07 20:05:38

Yield Return 和 Yield Break 的出现是为了简化迭代器。

类如果能被遍历则必须有IEnumerator<string> GetEnumerator() 方法, 并有用Yield Return

方法如果能被遍历则返回类型为 IEnumerable<string>,并有用Yield Return

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace TestYield
{
class Program
{
static void Main(string[] args)
{ foreach (string v in new Animal())
{
Console.WriteLine(v);
} foreach (string v in getList())
{
Console.WriteLine(v);
}
Console.ReadLine();
} static IEnumerable<string> getList()
{
yield return "cccc";
yield return "dddd";
} } public class Animal {
//类迭代必须要有的方法,使用Yield简化了迭代的实现
public IEnumerator<string> GetEnumerator()
{
yield return "aaaaa";
yield return "bbbbb";
} }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestYield
{
    class Program
    {
        static void Main(string[] args)
        {

foreach (string v in new Animal())
            {
                Console.WriteLine(v);
            }

foreach (string v in getList())
            {
                Console.WriteLine(v);
            }
            Console.ReadLine();
        }

static IEnumerable<string> getList()
        {
            yield return "cccc";
            yield return "dddd";
        }
      
    }

public class Animal {

public IEnumerator<string> GetEnumerator()
        {
            yield return "aaaaa";
            yield return "bbbbb";
        }

}
}