程序採取的動作會以語句表示。 一般動作包括宣告變數、指派值、呼叫方法、循環執行集合,以及根據指定的條件,分支至一或另一個程式代碼區塊。 在程式中執行語句的順序稱為控制流程或執行流程。 每次執行程式時,控制流程可能會有所不同,視程式在運行時間接收的輸入方式而定。
語句可以包含以分號結尾的單行程序代碼,或區塊中的一系列單行語句。 語句區塊會以括弧括住 {} ,而且可以包含巢狀區塊。 下列程式代碼顯示單行語句和多行語句區塊的兩個範例:
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# 關鍵字 / 附註 |
---|---|
宣告語句 | 宣告語句引進新的變數或常數。 變數宣告可以選擇性地將值指派給變數。 在常數宣告中,需要進行賦值。 |
表達式語句 | 計算值的表達式語句必須將值儲存在變數中。 |
選取範圍陳述式 | 選取語句可讓您根據一或多個指定的條件,分支至不同的程式代碼區段。 如需詳細資訊,請參閱下列主題: |
迴圈陳述式 | 迭代語句可讓您在陣列等集合中進行迴圈操作,或重複執行相同的語句集合,直到符合指定條件。 如需詳細資訊,請參閱下列主題: |
跳轉敘述句 | Jump 語句會將控制權傳送至另一個程式代碼區段。 如需詳細資訊,請參閱下列主題: |
例外狀況處理陳述式 | 例外處理語句可讓您在執行時發生的例外狀況中順利復原。 如需詳細資訊,請參閱下列主題: |
checked 和 unchecked |
checked 和 unchecked 語句可讓您指定當結果儲存在太小而無法保存結果值的變數中時,是否允許整數型別數值作業造成溢位。 |
await 陳述 |
如果您使用 async 修飾詞來標示方法,可以在方法中使用 await 運算子。 當控件到達 await 異步方法中的表達式時,控件會傳回給呼叫端,且方法中的進度會暫停,直到等候的工作完成為止。 當工作完成時,方法中的執行可以繼續。如需簡單的範例,請參閱 非同步方法章節。 如需詳細資訊,請參閱 使用 async 和 await 進行異步程序設計。 |
yield return 陳述 |
迭代器會對集合執行自訂的反覆項目,例如清單或陣列。 迭代器會使用 yield return 陳述式,一次傳回一個項目。 當到達yield return 語句時,會記住程式碼中的目前位置。 下次呼叫反覆運算器時,會從該位置重新啟動執行。如需詳細資訊,請參閱 Iterator。 |
fixed 陳述 |
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
}