除了前面介绍的几种循环语句外,C#同样也支持foreach循环,使用foreach可以遍历数组或者集合对象中的每一个元素。foreach会在每次循环的过程中,依次从数组或集合对象中取出一个新的元素放到foreach()里定义的变量中,直到所有元素都成功取出后退出循环。
代码示例如下:
int[] a = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
foreach(int i in a)
{
Console.Write("{0}", i);
}
Console.ReadLine();
运行结果: