C# Challenge 16 - 使用 C# 中的 switch-case 建構建立程式碼流程分支

C# Challenge 16 - 使用 C# 中的 switch-case 建構建立程式碼流程分支

Microsoft 2023 年所提供的 C# codecamp 基礎課程,總共有 38 個單元,完成後就可以獲得 Certification ,今天要來跟大家分享的是第 16 單元的內容。

本節內容

switch 陳述式

switch 功能與寫法

  • 都不符合才會進入到 default ,不論 default 是不是放在最後一個
  • 除非遇到 break ,不然會繼續比對下一個條件(return, throw 等也會直接離開 switch 區塊)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
int employeeLevel = 200;
string employeeName = "John Smith";

string title = "";

switch (employeeLevel)
{
case 100:
title = "Junior Associate";
break;
case 200:
title = "Senior Associate";
break;
case 300:
title = "Manager";
break;
case 400:
title = "Senior Manager";
break;
default:
title = "Associate";
break;
}

Console.WriteLine($"{employeeName}, {title}");

注意:選擇性 default 標籤可以出現在 switch 區段清單中的任何位置。 不過,大部分開發人員都會選擇將其放在最後一個位置,因為將 default 放在最後的選項更為合理 (邏輯上)。 不論位置為何,都會最後評估 default 區段。

多個 case 符合的狀況

可以將統一結果的條件寫在一起,如下面範例所示:

1
2
3
4
case 100:
case 200:
title = "Senior Associate";
break;

switch 語法練習

問題

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// SKU = Stock Keeping Unit. 
// SKU value format: <product #>-<2-letter color code>-<size code>
string sku = "01-MN-L";

string[] product = sku.Split('-');

string type = "";
string color = "";
string size = "";

if (product[0] == "01")
{
type = "Sweat shirt";
} else if (product[0] == "02")
{
type = "T-Shirt";
} else if (product[0] == "03")
{
type = "Sweat pants";
}
else
{
type = "Other";
}

if (product[1] == "BL")
{
color = "Black";
} else if (product[1] == "MN")
{
color = "Maroon";
} else
{
color = "White";
}

if (product[2] == "S")
{
size = "Small";
} else if (product[2] == "M")
{
size = "Medium";
} else if (product[2] == "L")
{
size = "Large";
} else
{
size = "One Size Fits All";
}

Console.WriteLine($"Product: {size} {color} {type}");

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// SKU = Stock Keeping Unit
string sku = "01-MN-L";

string[] product = sku.Split('-');

string type = "";
string color = "";
string size = "";

switch (product[0])
{
case "01":
type = "Sweat shirt";
break;
case "02":
type = "T-Shirt";
break;
case "03":
type = "Sweat pants";
break;
default:
type = "Other";
break;
}

switch (product[1])
{
case "BL":
color = "Black";
break;
case "MN":
color = "Maroon";
break;
default:
color = "White";
break;
}

switch (product[2])
{
case "S":
size = "Small";
break;
case "M":
size = "Medium";
break;
case "L":
size = "Large";
break;
default:
size = "One Size Fits All";
break;
}

Console.WriteLine($"Product: {size} {color} {type}");

重點整理

這個章節主要是讓大家練習如何使用 switch 的功能,相較於 if...else 的陳述式,在更多不同的條件下會大幅的提升可讀性。
有透過實際需求練習真的是還不錯,可以更知道兩者之間應該要如何轉換?
那我們下次見ʘ‿ʘ


參考資料

評論