MSDN上对yield关键字的示例

public class PowersOf2
{
    static void Main()
    {
        // Display powers of 2 up to the exponent of 8:
        foreach (int i in Power(2, 8))
        {
            Console.Write("{0} ", i);
        }
    }

    public static System.Collections.IEnumerable Power(int number, int exponent)
    {
        int result = 1;

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

    // Output: 2 4 8 16 32 64 128 256
}

从上例可见,Power是一个方法,它的返回值是IEnumerable类型。不过它没有直接返回一个IEnumerable类型的变量,而是采用了Yield Return的方法。外界对Power方法的返回值进行foreach迭代,则会使用到result变量的每次迭代所得到的不同的值。

public static class GalaxyClass
{
    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; }
    }
}

上例中,NextGalaxy是一个类的成员变量。成员变量一般都有get和set方法,这里get方法使用多个yield return语句等价替代了返回一个IEnumerable类型变量,特别赞。

我目前的认识比较浅,从MSDN的例子中目前也是略知一二,感觉C#在一些地方比Java还强啊,怎么大家都感觉Java程序员比较牛逼呢。其实我感觉还是Java跨平台、第三方库牛以及某些Java软件太强大的原因吧,如SSH框架,Hadoop,Tomcat等。所以,不是这个语言本身牛,还是语言的应用比较牛。

原文地址:https://www.cnblogs.com/shuada/p/3554878.html