c# - yield

来源:互联网 发布:linux黑客系统 编辑:程序博客网 时间:2024/05/17 03:44

yield关键字可以概括为一句话:对于返回值为集合的函数,使用yield return,可以每次返回集合中一个元素。

namespace YieldTest{    using System;    using System.Collections.Generic;    class Program    {        static void Main(string[] args)        {            // Call getter            Console.WriteLine("----Results of Get():");            foreach (var item in YieldTest.A)            {                Console.WriteLine(item);            }            // Call method            Console.WriteLine("----Results of Power():");            foreach(var result in YieldTest.Power(2, 10))            {                Console.WriteLine(result);            }        }    }    public class YieldTest     {        // Yield in Getter.        public static IEnumerable<string> A         {            get             {                yield return "Hello";                yield return "World";                yield return "I'm";                yield return "Yield";            }        }        // Yield in method.        public static IEnumerable<int> Power(int x, int exponent)        {            int result = 1;            for (int i = 0; i < exponent; i++)            {                result = result * x;                yield return result;            }        }    }}


0 0