class SomeData{public SomeData() { }
static public IEnumerable<SomeData> CreateSomeDatas(){return new List<SomeData> {new SomeData(),new SomeData(),new SomeData()};}}
同样的代码,它会逐项返回:
class SomeData{public SomeData() { }
static public IEnumerable<SomeData> CreateSomeDatas(){yield return new SomeData();yield return new SomeData();yield return new SomeData();}}
static void Main(string[] args){var store = new ContactYieldStore();var contacts = store.GetEnumerator();Console.WriteLine("Ready to iterate through the collection");Console.WriteLine("Hello {0}", contacts.First().FirstName);Console.ReadLine();}
static void Main(string[] args){testA();Console.Write("try again. the above won't execute any of the function!\n");
foreach (var x in testA()) { }
Console.ReadLine();}
// static List<int> testA()static IEnumerable<int> testA(){Console.WriteLine("asdfa");yield return 1;Console.WriteLine("asdf");}
public static IEnumerable<int> CreateCollectionWithList(){var list = new List<int>();list.Add(10);list.Add(0);list.Add(1);list.Add(2);list.Add(20);
return list;}
示例:使用收益即懒惰执行。
public static IEnumerable<int> CreateCollectionWithYield(){yield return 10;for (int i = 0; i < 3; i++){yield return i;}
yield return 20;}
现在当我调用这两个方法时。
var listItems = CreateCollectionWithList();var yieldedItems = CreateCollectionWithYield();
using System;using System.Collections.Generic;using System.Threading.Tasks;
public class Program{public static async Task Main(){List<int> numbers = new List<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
await foreach(int number in YieldReturnNumbers(numbers)){Console.WriteLine(number);}}
public static async IAsyncEnumerable<int> YieldReturnNumbers(List<int> numbers){foreach (int number in numbers){await Task.Delay(1000);yield return number;}}}