Yield:是一個關鍵字,經過狀態機實現,充分體現了延遲加載的特性。
下面是一個實例代碼,運行一下,會發現Yield的神奇之處。ide
class Program { static void Main(string[] args) { { IEnumerable<int> results = CommonMethod(); results = YieldMethod(); } Console.WriteLine("*******************************"); { IEnumerable<int> results = CommonMethod(); foreach (var item in results) { Console.WriteLine(item); } } Console.WriteLine("*******************************"); { IEnumerable<int> results = YieldMethod(); foreach (var item in results) { Console.WriteLine(item); } } Console.ReadKey(); } public static IEnumerable<int> CommonMethod() { List<int> results = new List<int>(); int counter = 0; int result = 1; while (counter++ < 10) { Thread.Sleep(1000); Console.WriteLine($"獲取{counter}次數據"); result = 2 * result; results.Add(result); } return results; } public static IEnumerable<int> YieldMethod() { int counter = 0; int result = 1; while (counter++ < 10) { Thread.Sleep(1000); Console.WriteLine($"獲取{counter}次數據"); result = 2 * result; yield return result; } } }