C#-一个特殊的迭代语句-yield

新建学习交流QQ群:1026682857 欢迎有兴趣的朋友 前来一起学习交流。

yield

yield 在语句中使用该关键字,表示出现的方法、运算符或者getter访问器是一个迭代器,使用 yield定义迭代器不需要额外的显示定义类型

//依次返回每一个元素
yield return <expression>;
//语句结束迭代
yield break;

*返回类型必须为IEnumerable,IEnumerable,IEnumerator,IEnumerator,且声明不能有in,ref,out参数
*返回的迭代器类型为object,如需要使用IEnumerable或者IEnumerator,则必须存在从表达式的类型到泛型类型参数的隐式转换
*不能再lambda表达式和匿名方法中使用该语句

官方代码示例

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.Generic.IEnumerable<int> 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
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值