请教foreach用法

catkit 2004-02-21 09:14:05
刚学c#,
这是c#帮助上关于foreach在集合中的用法的例子,看不懂,请大家指教
// statements_foreach_collections.cs
// Using foreach with C#-specific collections:
using System;

// Declare the collection:
public class MyCollection
{
int[] items;

public MyCollection()
{
items = new int[5] {12, 44, 33, 2, 50};
}

public MyEnumerator GetEnumerator()
{
return new MyEnumerator(this);
}

// Declare the enumerator class:
public class MyEnumerator
{
int nIndex;
MyCollection collection;
public MyEnumerator(MyCollection coll) //??
{
collection = coll;
nIndex = -1; //为什么要初始化为-1
}

public bool MoveNext()
{
nIndex++;
return(nIndex < collection.items.GetLength(0)); //返回bool型是
//为以后判断移动是否到头吗?
}

public int Current ///这是什么意思?是函数吗?
{
get
{
return(collection.items[nIndex]);
}
} ///
}
}

public class MainClass
{
public static void Main()
{
MyCollection col = new MyCollection();
Console.WriteLine("Values in the collection are:");

// Display collection items:
foreach (int i in col)
{
Console.WriteLine(i);
}
}
}
也不明白举这个例子说明什么,为什么会有
Values in the collection are:
12
44
33
2
50
这样的结果
...全文
2126 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复

110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧