yieid 使用笔记

实例代码:

 1 using System;
 2 using System.Collections;
 3 
 4 public class List
 5 {
 6 
 7     //来源: http://hi.baidu.com/jiang_yy_jiang
 8     public static IEnumerable Power(int number, int exponent)
 9     {
10         int counter = 0;
11         int result = 1;
12         while (counter++ < exponent)
13         {
14             result = result * number;
15             yield return result;
16         }
17     }
18 
19     static void Main()
20     {
22         foreach (int i in Power(2, 8))
23         {
24             Console.Write("{0} ", i);
25         }
26     }
27 }

 

yield 在迭代器块中用于向枚举数对象提供值或发出迭代结束信息号。

  yield return **; // 返回枚举值,

      yield break; // 发出迭代终止信号

yield语句只能出现在迭代器块中,该块可用作方法、运算符或访问器的体。这类方法、运算符或访问器的体受以下约束的控制:
        ■不允许不安全块。
        ■方法、运算符或访问器的参数不能是 ref 或 out。
        ■yield语句不能出现在匿名方法中。
        ■yield return语句不能出现在catch 块中或含有一个或多个catch子句的try块中。

yield语句的迭代块可以产生IEnumerator和IEnumerable两种对象:     

public IEnumerable<int> GetInts()
{
     yield return 0;
     yield return 1;
     yield return 2;
     yield return 3;
}

//可以直接在foreach语句中使用

foreach (int i in GetInts())
{
     Console.WriteLine(i.ToString());
}

// 输出结果为0123
public IEnumerator<int> GetEnumerator()//注意方法名
{
     yield return 0;
     yield return 1;
     yield break;  
     yield return 3;
}

 //IEnumerator无法直接用于foreach语句,所以可以使用如下语句


Integers ints = new Integers();//Integers是GetEnumerator()方法所在的类。
IEnumerator<int> enumerator = ints.GetEnumerator();

while (enumerator.MoveNext())
{
     Console.Write("{0} ", enumerator.Current.ToString());
}

// 输出结果为01

 

 

 

 

 

 

转载于:https://www.cnblogs.com/sunleinote/archive/2013/04/28/3049355.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值