语句是程序中最小程序指令。C#语言中可以使用多种类型的语句,每一种类型的语句又可以通过多个关键字实现。以下是C# 语言中使用的主要控制语句
类别 关键字
选择语句 if、else、switch、case
循环语句 do、for、foreach、in、while
跳转语句 break、continue、default、goto、return
异常处理语句 throw、try-catch、try-finally
检查和未检查语句 checked、unchecked
非保护和固定语句 unsafe、fixed
锁定语句 lock
一、选择语句
选择语句根据某个条件是否成立,来控制程序的执行流程。有两种结构的选择语句:
if-else 结构
switch-case 结构
if (expression)
statement1
[else
statement2]
if (x > )
if (y > )
Console.Write("Statement_1");
else
Console.Write("Statement_2");
if (x > )
{
if (y > )
Console.Write("Statement_1");
}
else
Console.Write("Statement_2");
if (Condition_1)
Statement_1;
else if (Condition_2)
Statement_2;
else if (Condition_3)
Statement_3;
……
else
Statement_n;
switch (<testVar>)
{
case <comparisonVal1>:
<如果<testVar>等于<comparisonVal1>时执行的语句>
break;
case <comparisonVal2>:
<如果<testVar>等于<comparisonVal2>时执行的语句>
break;
……
case <comparisonValN>:
<如果<testVar>等于<comparisonValN>时执行的语句>
break;
default:
<如果没有与<testVar>匹配的<comparisonValX>时执行的语句>
break;
}
using System;
class SwitchTest
{
static void Main()
{
int n = ;
switch(n)
{
case :
case :
case :
Console.WriteLine("It's 1, 2, or 3.");
break;
default:
Console.WriteLine("Not sure what it is.");
break;
}
}
}
It's 1, 2, or 3.
二、循环语句
语言中提供了以下4种循环语句:
· do-while
· for
· foreach-in
· while
do
{
statement
} while (expression);
// statements_do.cs
using System;
public class TestDoWhile
{
public static void Main ()
{
int x = ;
do
{
Console.WriteLine(x);
x++;
}
while (x < );
}
}
(二)for语句
for语句通常用来让一条语句或一个语句块执行一定的次数。for语句的一般形式:
for ([initializers]; [expression]; [iterators])
{
statement
}
其执行流程为:
首先初始化
initializers。接着,检查
expression。如果为 true,执行
statement,并重新计算循环计数器的值。如果为
false,则退出循环。返回上一步,继续执行。因为对 expression
的测试是在循环体执行之前,所以 for 语句可执行 0
次或多次。
语句的所有表达式都是可选的;例如,下列语句用于写一个无限循环:
for (;;)
{
...
}
// statements_for.cs
// for loop
using System;
class ForLoopTest
{
static void Main()
{
for (int i = ; i <= ; i++)
{
Console.WriteLine(i);
}
}
}
foreach (type identifier in expression)
{
staterment
}
int[] numbers = { , , , , , , -, -, };
foreach (int i in numbers)
{
System.Console.WriteLine(i);
}
foreach (ItemType item in myCollection)
myCollection 必须满足下面的要求。
while (expression)
{
statement
}
expression 表示 bool
类型的表达式。用来测试循环是否终止。statement
表示需要循环执行的语句。while 语句和 do-while 语句不同,do-while
是先执行循环体再判断条件,而 while 是先判断条件。如果条件为
true,则执行循环体,否则将跳过循环体,执行 while
块后面的代码。因此,while 语句中的循环体可能执行 0
次或多次。在
while 循环体中,可以使用 break、goto、reture 或 throw
语句跳出循环。如果要跳转到下一次循环,可在循环体中使用 continue
语句。
// statements_while.cs
using System;
class WhileTest
{
static void Main()
{
int n = ;
while (n < )
{
Console.WriteLine("Current value of n is {0}", n);
n++;
}
}
}
Current value of n is
Current value of n is
Current value of n is
Current value of n is
Current value of n is
三、 跳转语句
跳转语句用于从程序的一个地方把执行控制转移到另一个地方,每一条跳转语句的应用都会增加程序执行流程的分支。C#语言中可使用以下4种跳转语句:
· break
· continue
· goto
· return
(一) break 语句
break 语句用于中止当前执行的循环或它所在的 switch 语句,把控制交给循环或 switch 结构后面的语句。
示例:
在此例中,条件语句包含一个应该从 1 计数到 100 的计数器;但 break 语句在计数达到 4 后终止循环。
// statements_break.cs
using System;
class BreakTest
{
static void Main()
{
for (int i = ; i <= ; i++)
{
if (i == )
{
break;
}
Console.WriteLine(i);
}
}
}
输出:
下面的示例演示break在switch语句中的用法。
// statements_break2.cs
// break and switch
using System;
class Switch
{
static void Main()
{
Console.Write("Enter your selection (1, 2, or 3): ");
string s = Console.ReadLine();
int n = Int32.Parse(s); switch (n)
{
case :
Console.WriteLine("Current value is {0}", );
break;
case :
Console.WriteLine("Current value is {0}", );
break;
case :
Console.WriteLine("Current value is {0}", );
break;
default:
Console.WriteLine("Sorry, invalid selection.");
break;
}
}
}
输入 1,则示例输出为:
Enter your selection (, , or ):
Current value is
如果输入 4,则输出为:
Enter your selection (, , or ):
Sorry, invalid selection.
// statements_continue.cs
using System;
class ContinueTest
{
static void Main()
{
for (int i = ; i <= ; i++)
{
if (i < )
{
continue;
}
Console.WriteLine(i);
}
}
}
goto identifier;
goto case constant-expression;
goto default;
// statements_goto_switch.cs
using System;
class SwitchTest
{
static void Main()
{
Console.WriteLine("Coffee sizes: 1=Small 2=Medium 3=Large");
Console.Write("Please enter your selection: ");
string s = Console.ReadLine();
int n = int.Parse(s);
int cost = ;
switch (n)
{
case :
cost += ;
break;
case :
cost += ;
goto case ;
case :
cost += ;
goto case ;
default:
Console.WriteLine("Invalid selection.");
break;
}
if (cost != )
{
Console.WriteLine("Please insert {0} cents.", cost);
}
Console.WriteLine("Thank you for your business.");
}
}
Coffee sizes: =Small =Medium =Large
Please enter your selection:
Please insert cents.
Thank you for your business.
// statements_goto.cs
// Nested search loops
using System;
public class GotoTest1
{
static void Main()
{
int x = , y = ;
int count = ;
string[,] array = new string[x, y]; // Initialize the array:
for (int i = ; i < x; i++) for (int j = ; j < y; j++)
array[i, j] = (++count).ToString(); // Read input:
Console.Write("Enter the number to search for: "); // Input a string:
string myNumber = Console.ReadLine(); // Search:
for (int i = ; i < x; i++)
{
for (int j = ; j < y; j++)
{
if (array[i, j].Equals(myNumber))
{
goto Found;
}
}
} Console.WriteLine("The number {0} was not found.", myNumber);
goto Finish; Found:
Console.WriteLine("The number {0} is found.", myNumber); Finish:
Console.WriteLine("End of search.");
}
}
如果输入 44,则示例输出:
Enter the number to search for:
The number is found.
End of search.
(四) return 语句
return 语句终止所在方法的执行,并将程序的控制返回给调用它的方法。它还可以返回一个可选值。如果方法为 void 类型,可以省略 return 语句。return语句的形式如下:
return [expression];
其中:
expression 表示方法的返回值。当方法类型为 void 时不能使用 expression 参数。
示例:
在下面的示例中,方法 A() 以 double 值的形式返回变量 Area。
// statements_return.cs
using System;
class ReturnTest
{
static double CalculateArea(int r)
{
double area = r * r * Math.PI;
return area;
} static void Main()
{
int radius = ;
Console.WriteLine("The area is {0:0.00}", CalculateArea(radius));
}
}
输出:
The area is 78.54