您的位置:首页 > 其它

Jack's Notes5——foreach的本质(通过IEnumerable接口实现遍历)

2012-06-24 19:46 639 查看
class
Program
{
//5、Main函数中的内容是foreach的内部实现过程
static
void Main(string[] args)
{
//5.1实例化需要遍历的类,调用GetEnumerator()方法获得其可遍历的对象
MyColors colors = new MyColors();
IEnumerator colorEnumerator = colors.GetEnumerator();
//5.2使用MoveNext()方法和Current属性通过while循环实现foreach遍历
while (colorEnumerator.MoveNext())
{
Console.WriteLine(colorEnumerator.Current);
}
Console.ReadKey();
}
}

//1、定义一个实现了IEnumerable接口的类
class
MyColors:IEnumerable
{
public
string[] Colors = { "Red",
"Yellow", "Blue" };
//2、该类有GetEnumerator()方法,返回一个实现了IEnumerator接口的类,将需要遍历的值传入该类
public IEnumerator GetEnumerator()
{
return
new ColorEnumerator(Colors);
}
}

//3、该类实现了IEnumerator的Current属性和MoveNext()、Reset()方法,用于实现foreach遍历
class
ColorEnumerator:IEnumerator
{
string[] enumColors;

int index = -1;
//4、重写构造函数,使需要遍历的值可以通过构造函数传进来
public ColorEnumerator(string[] colors)
{
enumColors = new
string[colors.Length];
for (int i = 0; i < enumColors.Length; i++)
{
enumColors[i] = colors[i];
}
}

public
object Current
{
get {
return enumColors[index]; }
}

public
bool MoveNext()
{
if (index < enumColors.Length - 1)
{
index++;
return
true;
}
else
{
return
false;
}
}

public
void Reset()
{
index = -1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐