请教foreach用法
刚学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
这样的结果