zoukankan      html  css  js  c++  java
  • .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


  • 相关阅读:
    大话设计模式--中介者模式
    大话设计模式--职责链模式
    大话设计模式--命令模式
    大话设计模式--桥接模式
    迷宫求解
    stuct、class、typedef
    软件测试
    Scrapy初探
    python练习
    链表基础
  • 原文地址:https://www.cnblogs.com/configman/p/4657546.html
Copyright © 2011-2022 走看看