循环(Visual C# 速成版)

更新:2007 年 11 月

循环是指需要重复执行指定次数或直至满足某种条件为止的一条或一组语句。所使用的循环类型取决于编程任务和个人编码偏好。C# 和其他语言(如 C++)之间的一个主要区别就是 foreach 循环,该循环是为简化对数组或集合的循环访问而设计的。

foreach 循环

C# 引入了一种对于 C++ 和 C 程序员而言可能比较陌生的创建循环的方法:foreach 循环。foreach 循环不是简单地创建一个变量来索引一个数组或其他数据结构(如集合),而是为您做了一些困难的工作:

// An array of integers
int[] array1 = {0, 1, 2, 3, 4, 5};

foreach (int n in array1)
{
    System.Console.WriteLine(n.ToString());
}


// An array of strings
string[] array2 = {"hello", "world"};

foreach (string s in array2)
{
    System.Console.WriteLine(s);
}

for 循环

下面演示如何使用 for 关键字创建相同的循环:

// An array of integers
int[] array1 = {0, 1, 2, 3, 4, 5};

for (int i=0; i<6; i++)
{
    System.Console.WriteLine(array1[i].ToString());
}


// An array of strings
string[] array2 = {"hello", "world"};

for (int i=0; i<2; i++)
{
    System.Console.WriteLine(array2[i]);
}

while 循环

while 循环版本如下面的示例所示:

// An array of integers
int[] array1 = {0, 1, 2, 3, 4, 5};
int x = 0;

while (x < 6)
{
    System.Console.WriteLine(array1[x].ToString());
    x++;
}


// An array of strings
string[] array2 = {"hello", "world"};
int y = 0;

while (y < 2)
{
    System.Console.WriteLine(array2[y]);
    y++;
}

Do-While 循环

do-while 循环版本如下面的示例所示:

// An array of integers
int[] array1 = {0, 1, 2, 3, 4, 5};
int x = 0;

do
{
    System.Console.WriteLine(array1[x].ToString());
    x++;
} while(x < 6);


// An array of strings
string[] array2 = {"hello", "world"};
int y = 0;

do
{
    System.Console.WriteLine(array2[y]);
    y++;
} while(y < 2);

请参见

任务

如何:跳出循环语句 (Visual C#)

如何:循环访问集合 (Visual C#)

如何:循环访问数组 (Visual C#)

概念

C# 语言入门

参考

迭代语句(C# 参考)

对数组使用 foreach(C# 编程指南)