跳轉到內容

C# 程式設計/關鍵字/break

來自華夏公益教科書,開放的書籍,為開放的世界

關鍵字break用於退出迴圈或 switch 塊。

break 在迴圈中使用
int x;
 
while (x < 20){

   if (x > 10) break;

   x++;
}

只要 x 小於 20,while 迴圈就會增加 x。但是當 x 增加到 10 時,if 語句中的條件變為 true,因此 break 語句會導致 while 迴圈中斷,執行將在結束括號後繼續。

break 在 switch 塊中使用
int x;

switch (x)
    {
    case 0:
        Console.WriteLine("x is 0");
        break;
    case 1:
        Console.WriteLine("x is 1");
        break;
    case 2:
        // falls through
    case 3:
        Console.WriteLine("x is 2 or 3");
        break;
    }

當程式進入 switch 塊時,它將搜尋一個為真的 case 語句。一旦找到一個,它將讀取任何進一步的列印語句,直到找到一個 break 語句。在上面的例子中,如果x為 0 或 1,控制檯只會列印它們各自的值,然後跳出語句。然而,如果x的值是 2 3,程式將讀取相同的後續語句,直到到達 break 語句。為了不向任何閱讀程式碼的人展示 2 的處理方式與 3 相同,良好的程式設計習慣是在穿透 case 之後新增一個註釋,比如“穿透”。



C# 關鍵字
abstract as base bool break
byte case catch char checked
class const continue decimal default
delegate do double else enum
event explicit extern false finally
fixed float for foreach goto
if implicit in int interface
internal is lock long namespace
new null object operator out
override params private protected public
readonly ref return sbyte sealed
short sizeof stackalloc static string
struct switch this throw true
try typeof uint ulong unchecked
unsafe ushort using var virtual
void volatile while
C# 特殊識別符號(上下文關鍵字)
add alias async await dynamic
get global nameof partial remove
set value when where yield
上下文關鍵字(用於查詢)
ascending by descending equals from
group in into join let
on orderby select where
華夏公益教科書