结合使用,表示迭代结束。

这类方法、运算符或访问器的体受以下约束的控制:

不允许不安全块。

out。

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

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

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

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

 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

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-02
猜你喜欢
  • 2022-12-23
  • 2021-09-21
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案