IEnumerable 和 IEnumerator 接口的作用

IEnumerable:
实现IEnumerable接口的类,可以支持foreach循环遍历对象的集合元素

IEnumerator GetEnumerator()返回可循环访问集合的枚举数。


IEnumerator:

object Current获取集合中的当前元素。
bool MoveNext()将枚举数推进到集合的下一个元素。
如果枚举数成功地推进到下一个元素,则为 true;如果枚举数越过集合的结尾,则为 false
void Reset()

将枚举数设置为其初始位置,该位置位于集合中第一个元

using System;
using System.Collections;

namespace ConsoleApplication1
ExpandedBlockStart.gifContractedBlock.gif
{
ExpandedSubBlockStart.gifContractedSubBlock.gif
/**//// <summary>
/// Summary description for Class1.
/// </summary>

class Class1
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
ExpandedSubBlockStart.gifContractedSubBlock.gif
/**//// <summary>
/// The main entry point for the application.
/// </summary>

[STAThread]
static void Main(string[] args)
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
CStringEnum se
= new CStringEnum();

foreach (string s in se)
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
Console.WriteLine(s);
}


Console.Read() ;
}

}


class CStringEnum : IEnumerable, IEnumerator
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
string[] items = new string[16];
int index = -1;

public CStringEnum()
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
for(int i=0; i<items.Length; ++i)
items[i]
= "s" + i.ToString();
}


ContractedSubBlock.gifExpandedSubBlockStart.gif
IEnumerable Members#region IEnumerable Members

public IEnumerator GetEnumerator()
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
// TODO: Add StringCollection.GetEnumerator implementation
return (IEnumerator)this;
}


#endregion


ContractedSubBlock.gifExpandedSubBlockStart.gif
IEnumerator Members#region IEnumerator Members

public void Reset()
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
// TODO: Add CStringEnum.Reset implementation
index = -1;
}


public object Current
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
get
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
// TODO: Add CStringEnum.Current getter implementation
return items[index];
}

}


public bool MoveNext()
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
// TODO: Add CStringEnum.MoveNext implementation
index++;
return index >= items.Length ? false : true;
}


#endregion

}


}

转载于:https://www.cnblogs.com/XiaoJie85/articles/2217159.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值