C#中的yield关键字

本文详细介绍了C#中的yield关键字用法及其在迭代器函数中的应用。通过两个实例展示了如何利用yield return和yield break来高效地实现迭代查询。同时,文章还列举了使用yield关键字的一些注意事项。

整理翻译自:http://msdn.microsoft.com/zh-cn/library/9k7k7cf0.aspx

1.yield return // 迭代查询查询返回和中断处,语句可一次返回一个元素

2.yield break; // 终止迭代查询

Yield关键字后程序的执行过程:
Typical Implementation:
1).Caller calls function
2).Function executes and returns list 返回一个列表
3).Caller uses list 对列表进行操作

Yield Implementation:
1).Caller calls function
2).Caller requests item 按需请求一个元素
3).Next item returned 返回请求的元素
4).Goto step #2

实例1:
   class JYTestYield
    {
        static void Main(string[] args)
        {
            // Display powers of 2 up to the exponent of 8:
            foreach (int i in Power(2, 8))
            {
                Console.Write("{0} ", i);

            }

            // Output value:2 4 8 16 32 64 128 256
            while (true);
        }

        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;// 前面执行到的位置, 下一个请求会从这里开始.
            }
        }
    }

实例2:
 class JYTestYield
    {
        static void Main(string[] args)
        {
            // Display powers of 2 up to the exponent of 8:
            Galaxies galaxObj = new Galaxies();
            foreach (Galaxy g in galaxObj.NextGalaxy)
            {
                Console.Write("name: " + g.Name + ", Years: " + g.MegaLightYears.ToString() + "\n");
            }

            while (true) ;
        }
    }

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

注意事项:

yield函数:

使用yield的返回迭代器函数条件(其它类型的函数也可以使用yield):

返回类型必须为 IEnumerable、IEnumerable<T>、IEnumerator 或 IEnumerator<T>。
该声明不能有任何 ref 或out参数。

你不能在具有以下特点的方法中包含 yield return 或 yield break 语句:
匿名方法。
包含不安全的块的方法。

异常处理:
不能将 yield return 语句置于 try-catch 块中。 可将 yield return 语句置于 try-finally 语句的 try 块中。
yield break 语句可以位于 try 块或 catch 块,但不能位于 finally 块。
如果 foreach 主体(在迭代器方法之外)引发异常,则将执行迭代器方法中的 finally 块。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值