yield用法的一點理解

yield 關鍵字與 return 關鍵字結合使用,向枚舉器對象提供值。這是一個返回值,例如,在 foreach 語句的每一次循環中返回的值。yield 關鍵字也可與 break 結合使用,表示迭代結束。web

yield 語句只能出如今 iterator 塊中,這種塊可做爲方法、運算符或訪問器的主體實現。這類方法、運算符或訪問器的體受如下約束的控制:安全

不容許不安全塊。spa

方法、運算符或訪問器的參數不能是 ref  outcode

yield return 語句不能放在 try-catch 塊中的任何位置。orm

該語句可放在後跟 finally 塊的 try 塊中。對象

yield break 語句可放在 try 塊或 catch 塊中,但不能放在 finally 塊中。blog

yield 語句不能出如今匿名方法中。ci

 internal class Program
    {
        private static void Main()
        {
            ShowGalaxies();
            foreach (int i in Power(2, 8))
            {
                Console.Write("{0} ", i);
            }
            List<string> names = new List<string>();
            names.Add("fy");
            names.Add("sky");
            names.Add("sky");
            IEnumerable aa = FindBobs(names);
            foreach (var i in aa)
            {
                Console.WriteLine(i.ToString());
            }
        }

        private static IEnumerable<string> FindBobs(IEnumerable<string> names)
        {
            foreach (var currName in names)
            {
                if (currName == "sky")
                {
                    yield return currName;
                }
            }
        }

        private static IEnumerable Power(int number, int exponent)
        {
            int counter = 0;
            int result = 1;
            while (counter++ < exponent)
            {
                result = result * number;
                yield return result;
            }
        }

        public static void ShowGalaxies()
        {
            var theGalaxies = new Galaxies();
            foreach (Galaxy theGalaxy in theGalaxies.NextGalaxy)
            {
                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.aspxget

相關文章
相關標籤/搜索