yield用法的一点理解

yield 关键字与 return 关键字结合使用,向枚举器对象提供值。这是一个返回值,例如,在 foreach 语句的每一次循环中返回的值。yield 关键字也可与 break 结合使用,表示迭代结束。

yield 语句只能出现在 iterator 块中,这种块可作为方法、运算符或访问器的主体实现。这类方法、运算符或访问器的体受以下约束的控制:

不允许不安全块。

方法、运算符或访问器的参数不能是 ref  out

yield return 语句不能放在 try-catch 块中的任何位置。

该语句可放在后跟 finally 块的 try 块中。

yield break 语句可放在 try 块或 catch 块中,但不能放在 finally 块中。

yield 语句不能出现在匿名方法中。

 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.aspx

原文地址:https://www.cnblogs.com/skysimblog/p/3540632.html