.net yield关键字 分类: .NET 2014-05-13 11:02 609人阅读 评论(0) 收藏

static void Main(string[] args)
        {
            //输出:2 4 8 16 32 64 128 256
            foreach (int i in Power(2, 8))
            {
                Console.Write("{0} ", i);
            }
        }
        public static IEnumerable<int> Power(int number, int exponent)
        {
            int result = 1;

            for (int i = 0; i < exponent; i++)
            {
                result = result * number;
                yield return result;
            }
        }


 /// <summary>
        /// 输出:
        /// Tadpole 400
        /// Pinwheel 25
        /// Milky Way 0
        /// Andromeda 3
        /// </summary>
        public static void ShowGalaxies()
        {
            var theGalaxies = new Galaxies();
            foreach (Galaxy theGalaxy in theGalaxies.NextGalaxy)
            {
                System.Diagnostics.Debug.WriteLine(theGalaxy.Name + " " + theGalaxy.MegaLightYears.ToString());
            }
        }

        public class Galaxies
        {
            public System.Collections.Generic.IEnumerable<Galaxy> NextGalaxy
            {
                get
                {
                    yield return new Galaxy { Name = "Tadpole", MegaLightYears = 400 };
                    yield return new Galaxy { Name = "Pinwheel", MegaLightYears = 25 };
                    yield return new Galaxy { Name = "Milky Way", MegaLightYears = 0 };
                    yield return new Galaxy { Name = "Andromeda", MegaLightYears = 3 };
                }
            }
        }

        public class Galaxy
        {
            public String Name { get; set; }
            public int MegaLightYears { get; set; }
        }

http://msdn.microsoft.com/zh-cn/library/9k7k7cf0.aspx


原文地址:https://www.cnblogs.com/configman/p/4657546.html