// 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;
} public bool MoveNext()
{
nIndex++;
return(nIndex < collection.items.GetLength(0));
} 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
// 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;
} public bool MoveNext()
{
nIndex++;
return(nIndex < collection.items.GetLength(0));
} 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
{
//
}
foreach(string b in a)
{
//循環三次﹐﹐a的值分別為a,b,c
}
包装了一下
用起来更方便
{}
foreach(string xxx in string[]...)
foreach(int xxx in int[]...)
foreach(char xxx in char[]...)
foreach(... in ...S)