【C#】yield使用

时间:2024-04-11 15:46:46
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ConsoleApp15 { internal class Program { static void Main(string[] args) { IEnumerable<int> fibonaccis = Fibonacci(10); foreach (var f in fibonaccis) { Console.Write("{0} ", f); } IEnumerable<int> fibonaccis1 = FibonacciYield(10); foreach (var f in fibonaccis1) { Console.Write("{0} ", f); } Console.ReadLine(); } public static List<int> Fibonacci(int count) { int p = 1; int c = 1; List<int> result = new List<int>(); for (int i = 0; i < count; i++) { result.Add(p); Thread.Sleep(500); int temp = p + c; p = c; c = temp; } return result; } public static IEnumerable<int> FibonacciYield(int count) { int p = 1; int c = 1; for (int i = 0; i < count; i++) { yield return p; Thread.Sleep(500); int temp = p + c; p = c; c = temp; } } } }