程序的操作通过语句来表示。 常见作包括声明变量、赋值、调用方法、循环访问集合以及分支到一个或多个代码块,具体取决于给定条件。 在程序中执行语句的顺序称为控制流或执行流。 每次运行程序时,控制流都可能有所不同,具体取决于程序在运行时接收的输入的反应。
语句可以包含以分号结尾的单个代码行,或块中的一系列单行语句。 语句块括在括号中 {} ,可以包含嵌套块。 以下代码显示了单行语句和多行语句块的两个示例:
public static void Main()
{
// Declaration statement.
int counter;
// Assignment statement.
counter = 1;
// Error! This is an expression, not an expression statement.
// counter + 1;
// Declaration statements with initializers are functionally
// equivalent to declaration statement followed by assignment statement:
int[] radii = [15, 32, 108, 74, 9]; // Declare and initialize an array.
const double pi = 3.14159; // Declare and initialize constant.
// foreach statement block that contains multiple statements.
foreach (int radius in radii)
{
// Declaration statement with initializer.
double circumference = pi * (2 * radius);
// Expression statement (method invocation). A single-line
// statement can span multiple text lines because line breaks
// are treated as white space, which is ignored by the compiler.
System.Console.WriteLine($"Radius of circle #{counter} is {radius}. Circumference = {circumference:N2}");
// Expression statement (postfix increment).
counter++;
} // End of foreach statement block
} // End of Main method body.
} // End of SimpleStatements class.
/*
Output:
Radius of circle #1 = 15. Circumference = 94.25
Radius of circle #2 = 32. Circumference = 201.06
Radius of circle #3 = 108. Circumference = 678.58
Radius of circle #4 = 74. Circumference = 464.96
Radius of circle #5 = 9. Circumference = 56.55
*/
语句类型
下表列出了 C# 中的各种类型的语句及其关联的关键字,并提供了包含详细信息的主题的链接:
类别 | C# 关键字/备注 |
---|---|
声明语句 | 声明语句引入了新的变量或常量。 变量声明可以选择为变量赋值。 在常量声明中必须赋值。 |
表达式语句 | 计算值的表达式语句必须将值存储在变量中。 |
选择语句 | 选择语句使你可以根据一个或多个指定的条件分支到不同的代码部分。 有关详细信息,请参阅以下主题: |
迭代语句 | 使用迭代语句可以循环访问数组等集合,或重复执行同一组语句,直到满足指定的条件。 有关详细信息,请参阅以下主题: |
跳转语句 | 跳转语句将控制权传输到另一个代码部分。 有关详细信息,请参阅以下主题: |
异常处理语句 | 异常处理语句用于从运行时发生的异常情况正常恢复。 有关详细信息,请参阅以下主题: |
checked 和 unchecked |
使用 checked and unchecked 语句可以指定是否允许整型数值运算在结果存储在太小而无法保存结果值的变量中时导致溢出。 |
await 语句 |
如果用 async 修饰符标记方法,则可以在该方法中使用 await 运算符。 当控制权到达异步方法中的 await 表达式时,控制权将返回给调用方,方法执行进度将挂起,直到所等待的任务完成。 任务完成后,可以在方法中恢复执行。有关简单示例,请参阅 方法的“异步方法”部分。 有关详细信息,请参阅 使用 async 和 await 的异步编程。 |
yield return 语句 |
迭代器对集合执行自定义迭代,如列表或数组。 迭代器使用 yield return 语句返回元素,每次返回一个。 到达 yield return 语句时,会记住当前在代码中的位置。 下次调用迭代器时,将从该位置重启执行。有关更多信息,请参见 迭代器。 |
fixed 语句 |
固定语句可防止垃圾回收器重新定位可移动变量。 有关详细信息,请参阅 “已修复”。 |
lock 语句 |
使用 lock 语句,一次只能将代码块的访问限制为一个线程。 有关详细信息,请参阅 锁定。 |
带标签的语句 | 可以给语句一个标签,然后使用 goto 关键字跳转到标记的语句。 (请参阅以下行中的示例。 |
空语句 | 空语句由一个分号组成。 不执行任何操作,可以在需要语句但不需要执行任何操作的地方使用。 |
声明语句
下面的代码示例展示了带初始赋值和不带初始赋值的变量声明示例,以及具有必要初始化的常量声明。
// Variable declaration statements.
double area;
double radius = 2;
// Constant declaration statement.
const double pi = 3.14159;
表达式语句
以下代码演示表达式语句的示例,包括赋值、使用赋值创建对象以及方法调用。
// Expression statement (assignment).
area = 3.14 * (radius * radius);
// Expression statement (result discarded).
int x = 0;
x++;
// Expression statement (method invocation).
System.Console.WriteLine();
// Expression statement (new object creation).
System.Collections.Generic.List<string> strings =
new System.Collections.Generic.List<string>();
空语句
以下示例显示了空语句的两个用途:
void ProcessMessages()
{
while (ProcessMessage())
; // Statement needed here.
}
void F()
{
//...
if (done) goto exit;
//...
exit:
; // Statement needed here.
}
嵌入式语句
例如,某些语句(例如 迭代语句)始终有一个遵循它们的嵌入语句。 此嵌入语句可以是一个语句,也可以是一个语句块,由{}括号括起多个语句。 即使是单行嵌入语句也可以括在括号中 {} ,如以下示例所示:
// Recommended style. Embedded statement in block.
foreach (string s in System.IO.Directory.GetDirectories(
System.Environment.CurrentDirectory))
{
System.Console.WriteLine(s);
}
// Not recommended.
foreach (string s in System.IO.Directory.GetDirectories(
System.Environment.CurrentDirectory))
System.Console.WriteLine(s);
未括在括号中的 {} 嵌入语句不能是声明语句或带标签的语句。 下面的示例对此进行了演示:
if(pointB == true)
//Error CS1023:
int radius = 5;
将嵌入语句放在块中以修复错误:
if (b == true)
{
// OK:
System.DateTime d = System.DateTime.Now;
System.Console.WriteLine(d.ToLongDateString());
}
嵌套语句块
语句块可以嵌套,如以下代码所示:
foreach (string s in System.IO.Directory.GetDirectories(
System.Environment.CurrentDirectory))
{
if (s.StartsWith("CSharp"))
{
if (s.EndsWith("TempFolder"))
{
return s;
}
}
}
return "Not found.";
无法访问的语句
如果编译器确定控制流在任何情况下都无法访问特定语句,它将生成警告 CS0162,如以下示例所示:
// An over-simplified example of unreachable code.
const int val = 5;
if (val < 4)
{
System.Console.WriteLine("I'll never write anything."); //CS0162
}
C# 语言规范
另请参阅
- 语句关键字
- C# 运算符和表达式