控制程序流的语句,它们不是按代码在程序中的排列位置顺序执行的
条件语句:
常见的条件语句有下面几种。
1. if语句
对于条件分支,C#继承了C和C++的if...else结构。对于用过程语言编程的人来说,其语法是非常直观的:
if (condition)
{statement(s)}
else
{statement(s)}
2. switch语句
witch…case语句适合于从一组互斥的分支中选择一个执行分支;该语句类似于Visual Basic中的Select Case语句。
switch (integerA)
{
case 1:
Console.WriteLine("integerA =1");
break;
case 2:
Console.WriteLine("integerA =2");
break;
case 3:
Console.WriteLine("integerA =3");
break;
default:
Console.WriteLine("integerA is not 1,2, or 3");
break;
}
switch(country)
{
case "au":
case "uk":
case "us":
language = "English";
break;
case "at":
case "de":
language = "German";
break;
}
注意case的值必须是常量表达式--不允许使用变量
循环
1.for循环
C#的for循环提供的迭代循环机制是在执行下一次迭代前,测试是否满足某个条件,其语法如下:
for (initializer; condition; iterator)
statement(s)
2. while循环
while循环与C++和Java中的while循环相同,与Visual Basic中的While...Wend循环相同。与for循环一样,while也是一个预测试的循环。其语法是类似的,但while循环只有一个表达式:
while(condition)
statement(s);
3. do…while循环
bool condition;
do
{
// This loop will at least execute once, even if Condition is false.
MustBeCalledAtLeastOnce();
condition = CheckCondition();
} while (condition);
4. foreach循环
foreach循环可以迭代集合中的每一项。
foreach (int temp in arrayOfInts)
{
Console.WriteLine(temp);
}
注意,foreach循环不能改变集合中各项(上面的temp)的值