.Net 2.0 新功能:迭代器(Iterators)

本文介绍了迭代器的概念及其在类或结构中支持foreach迭代的应用方式。通过具体示例解释了如何使用yield return语句来逐个返回元素,以及yield break语句的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

什么是迭代器?

迭代器是方法、get访问器或运算符,它能使您能够在类或者结构中支持foreach迭代,而不必实现整个IEnumerable接口。

例子:

publicclassYieldTest

...{

publicstaticIEnumertablePower(intnumber,intexponent)

...{

intcounter=0;

intresult=1;

while(counter++<exponent)

...{

result
=result*number

yieldreturnresult

}


}


}


<!--[if !supportLists]-->1. <!--[endif]-->迭代器是可以返回相同类型的值的有序序列的一段代码

<!--[if !supportLists]-->2. <!--[endif]-->迭代器可用作方法、运算符或get访问器的代码体

<!--[if !supportLists]-->3. <!--[endif]-->迭代器代码使用yield return语句一次返回每个元素

<!--[if !supportLists]-->4. <!--[endif]-->yield break将终止迭代

<!--[if !supportLists]-->5. <!--[endif]-->可以在类中实现做个迭代器。每个迭代器都必须像任何类成员一样有唯一的名称,并且可以在foreach语句中可调用

<!--[if !supportLists]-->6. <!--[endif]-->迭代器的返回类型必须为IEnumerableIEnumberatorIEnumerbale<T>或者IEnumberator<T>

foreach(int i in YieldTest. Power)

{

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值