從 Visual Studio 建立第一個專案,到變數、判斷、迴圈與類別,這篇收集我學習 C# 時整理的範例。各章搭配原有的 Learning 專案編號,方便在閱讀說明與操作程式之間切換。

本篇重點
  • 建立 .NET 桌面開發環境與專案
  • 從變數、判斷和迴圈逐步理解程式流程
  • 搭配類別、存取修飾詞與除錯操作練習

原始實作記錄於 2020 年;以下操作畫面與程式範例保留當時版本。

C# 學習相關檔案下載參考,網址:請點我一下 。


軟體安裝 和 建立方案 / 專案

軟體安裝

官網軟體下載:https://visualstudio.microsoft.com/zh-hant/downloads/

  1. 本文使用 Visual Studio 2019 示範,保留當時的畫面。重做練習時,選擇適合自己專案的版本與授權方案。
  • 軟件安裝:原文圖片 01
  1. C# 這邊用的是.NET桌面開發,如果還需要其他工作負載,可以自行選擇下載。
  • 軟件安裝:原文圖片 02

建立方案 / 專案

  • 創建方案 / 專案:原文圖片 03

使用註解幫助閱讀程式碼

資料參考專案 Learning 01。

  1. 單行註解
    1
    // 單行註釋:幫助程序開發者用於閱讀代碼
  2. 多行註解
    1
    2
    3
    /* 多行註釋:幫助程序開發者用於閱讀代碼
    多行註釋:幫助程序開發者用於閱讀代碼
    多行註釋:幫助程序開發者用於閱讀代碼 */
    3.摺疊註解
    1
    2
    #region 摺疊註釋
    #endregion
  3. 文件註解
    當滑鼠指標移動到Tset文字時,視窗註解會顯示文檔註釋。
    1
    2
    3
    4
    /// <summary>
    /// 文檔註釋
    /// </summary>
    public static void Test(){}

常用快捷鍵

  1. 新增新專案
    在該專案裡面,按Ctrl + Shift + N,即可跳出建立新專案的視窗。
  2. 新增檔案
    在專案中按Ctrl + N,可開啟新增檔案的視窗。
  3. 加入新增專案項目
    在該專案裡面,按Ctrl + Shift + A,即可跳出新增項目的視窗。
  4. 加入現有專案項目
    在該專案裡面,按Shift + Alt + A,即可跳出加入現有項目的視窗。
  5. 區域註解
    Ctrl + K + C 選取區域註解
    Ctrl + K + U 選取區域取消註解
  6. Console.WriteLine()
    鍵盤輸入cw,即可跳出Console.WriteLine();

變數理解與使用

先看每個變數保存什麼值,再確認輸出時是數值運算還是文字串接。下方保留原範例的變數名稱,可逐項改值並比較輸出。

資料參考專案 Learning 02。

操作說明

資料型態值:

1
2
3
4
5
int number;                          // 宣告int類別的變數
number = 1000; // number可分行建置數字
double Decimalpoint = 999.0000001; // 宣告double類別的變數
char print = '字'; // 單個字符,用'單引號'
string Type = "我是文字"; // 字串,用"雙引號"
  1. 方法一:用 + 組合輸出。數值相加會先做運算;當其中一個運算元是 string 時,才進行字串串接。char 相加並不等同於字串串接。
    char print 的print若直接與數值相加,會參與數值運算;若想輸出字元本身,需留意串接順序。
    string Type 的Type 可觸發字串串接,但前面已發生的數值相加仍會先完成。

    1
    Console.WriteLine(number + Decimalpoint + " " + Type + print);
  2. (方法2) 格式預留位置用法:(“{0}、{1}、{2}、{3}、{4}”, 0, 1, 2, 3, 4);

    1
    Console.WriteLine("數字:{0}  , 小數點:{1}  , 字符:{2}  , 字串:{3}", number, Decimalpoint, print, Type);
  • 顯示輸出字元

    1
    2
    Console.Write("Hello World!");       // 印字
    Console.WriteLine("Hello World!"); // 換行印字
  • 鍵盤輸入字元

    1
    2
    Console.Read();                      // 等待輸入
    Console.ReadLine("Hello World!"); // 換行輸入

變數的命名規則

資料參考專案 Learning 03。

  1. Pascal 帕斯卡命名:當有多個單字組成變數或方法時,每個單字的開頭字母要大寫。
    (常用處:類名、屬性、方法名、介面)
    1
    string UserNameTest;
  2. 駝峰命名:多個單字出現,首單字開頭字母要小寫,其餘單字開頭字母要大寫。
    1
    string nameYongCheng;
  3. C# 變數:常見命名使用字母、數字與底線,首字元不能是數字,並避開保留字。C# 也支援部分 Unicode 字元;入門練習先採用清楚、一致的英文名稱。
    1
    int _age1;
  4. 見名知意
    1
    string name = "黃永成";

運算子的優先級別使用

資料參考專案 Learning 04。

  1. 算術運算子 + - * / %
    (加、減、乘、除、餘)
  2. 關係運算子 > < == >= <= !=
    (大於、小於、相同、大於等於、小於等於、不同)
  3. 邏輯運算子 && || !
    (and閘、or閘、not閘)
  4. 賦值運算子 =
    (int number = 1;)

格式化輸出的使用方式

資料參考專案 Learning 05。

操作說明

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// C#占位符的使用
#region 資料數值
Console.Write("請輸入帳號:");
string User = Console.ReadLine();
string password = "password";
#endregion

// 方法一
Console.WriteLine("帳號:{0}",User);

// 方法二
string good = string.Format("您輸入的帳號是:{0}", User);
Console.WriteLine(good);

// 方法三
string nice = $"輸入的帳號是:{User},輸入的密碼是:{password}";
Console.WriteLine(nice);

// 方法四
string great = "帳號是:" + $"{User}" + " | 密碼是:" + $"{password}";
Console.WriteLine(great);

// 任何按鍵跳脫
Console.Read();

if else 判斷式的使用方式

先把條件寫成布林判斷,再安排成立與不成立時的動作。原例使用下雨與存款等教學情境;也要測試恰好等於門檻的值,確認比較運算子涵蓋的範圍。

資料參考專案 Learning 06。

操作說明

情境一

假如條件是:下雨天
有下雨的話:不出門
沒下雨的話:出門

  • 程式碼:
    1
    2
    3
    4
    5
    bool rain=true; // 布林值: true真、false假
    if (rain==true)
    { Console.WriteLine("不出門"); }
    else
    { Console.WriteLine("要出門"); }

情境二

假如條件是:你存款的錢有80萬元
若低於80萬元:我的女兒不能嫁給你
若高於80萬元:我的女兒才能嫁給你

  • 程式碼:
    1
    2
    3
    4
    5
    6
    7
    8
    Console.Write("請說出你的存款金額:");
    int money = int.Parse(Console.ReadLine());
    // Console.ReadLine()是字串,需使用int.Parse轉成數字。
    bool result = money >= 800000; // 布林值: true真、false假
    if (money >= 800000)
    { Console.WriteLine("我的女兒可以嫁給你"); }
    else
    { Console.WriteLine("我的女兒不可以嫁給你"); }

情境三

假如條件是:你存款的錢有80萬元,有房子,有車,沒老婆
若低於80萬元:我的女兒不能嫁給你
若高於80萬元:我的女兒才能嫁給你

  • 條件宣告程式碼:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    // 條件宣布    
    Console.Write("請說出你的存款金額:");
    int money_2 = int.Parse(Console.ReadLine());
    // Console.ReadLine()是字串,需使用int.Parse轉成數字。
    // 布林值: true真、false假
    bool result_2 = money_2 >= 800000;
    bool room = true;
    bool car = true;
    bool wife = false;
  1. 方法一:
    1
    2
    3
    4
    if (room && car &&!wife && result_2)
    { Console.WriteLine("我的女兒可以嫁給你"); }
    else
    { Console.WriteLine("我的女兒不可以嫁給你"); }
  2. 方法二:
    1
    2
    3
    4
    5
    if (result_2 != true) { Console.WriteLine("我的女兒不可以嫁給你!"); }
    else if (room != true) { Console.WriteLine("有房子再說吧~"); }
    else if (car != true) { Console.WriteLine("有車再說吧~"); }
    else if (wife != false) { Console.WriteLine("先離婚再說~"); }
    else { Console.WriteLine("我的女兒可以嫁給你!"); }
  3. 方法三:
    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
    if (result_2 == true)
    {
    if (room == true)
    {
    if (car == true)
    {
    if (wife == false)
    {
    Console.WriteLine("我的女兒可以嫁給你");
    }
    else
    {
    Console.WriteLine("我的女兒不可以嫁給你");
    }
    }
    else
    {
    Console.WriteLine("我的女兒不可以嫁給你");
    }
    }
    else
    {
    Console.WriteLine("我的女兒不可以嫁給你");
    }
    }
    else
    {
    Console.WriteLine("我的女兒不可以嫁給你");
    }

switch 和 if 的差別

if 適合以布林條件處理範圍與組合條件;switch 可依輸入值安排對應分支。本節保留年齡分類練習,閱讀時核對每個區間是否重疊或遺漏。

資料參考專案 Learning 07。

操作說明

條件:

告訴我你的年齡
幼稚園:3~5歲
國小:6~11歲
國中:12~14歲

  • 條件宣告程式碼:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    // 條件宣布
    Console.Write("請輸入您的年齡:");
    //int age = int.Parse(Console.ReadLine());
    int age;
    bool good = int.TryParse(Console.ReadLine(),out age);
    if (good)
    {
    Console.Write("您的年齡是:");
    Console.WriteLine(age+"歲");
    }
    else
    {
    Console.WriteLine("你填錯了,請填數字就好");
    System.Environment.Exit(0); // 終止所有程序
    }

    bool Kindergarten = 6 > age && age >= 3;
    bool ElementarySchool = 12 > age && age >= 6;
    bool secondary = 15 > age && age >= 12;
  1. 方法一:
    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
    // 方法一
    Console.Write("方法一:");
    switch (age) // 選擇
    {
    case 3:
    case 4:
    case 5:
    Console.WriteLine("我要上幼稚園了");
    break; // 跳脫
    case 6:
    case 7:
    case 8:
    case 9:
    case 10:
    case 11:
    Console.WriteLine("我要上小學了");
    break; // 跳脫
    case 12:
    case 13:
    case 14:
    Console.WriteLine("我要上國中了");
    break; // case 最後一項一定要加break;

    default: // 默認:沒有指定的case
    Console.WriteLine("我來亂的");
    break;
    }
  2. 方法二:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    // 方法二
    if (Kindergarten == true) // 判斷
    {
    Console.Write("方法二:");
    Console.WriteLine("可以上幼稚園了");
    }
    else if (ElementarySchool == true)
    {
    Console.Write("方法二:");
    Console.WriteLine("可以上國小了");
    }
    else if (secondary == true)
    {
    Console.Write("方法二:");
    Console.WriteLine("可以上國中了");
    }
    else
    {
    Console.Write("方法二:");
    Console.WriteLine("我來亂的");
    }

【練習題】C# 綜合基礎語法

資料參考專案 Learning 08。

操作說明

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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// 友善訊息
Console.WriteLine("################永成銀行網銀登入################");

// 銀行ATM網銀
// 輸入用戶帳密
Console.Write("請輸入帳號:");
string User = Console.ReadLine();
Console.Write("請輸入密碼:");
string password = Console.ReadLine();

// 用戶帳密設置
string User_test = "pkpk26261";
string password_test = "12345678";

// 資料值核對
bool User_good = User == User_test;
bool password_good = password == password_test;

if (User_good && password_good)
{
Console.WriteLine("登入成功");
Console.WriteLine("請輸入數字,選擇服務選項: 1.查詢餘額 2.提款 3.轉帳 4.存款");
int number;
bool nice = int.TryParse(Console.ReadLine(),out number);
if (nice != true)
{
Console.WriteLine("無此服務項目");
System.Environment.Exit(0); // 終止所有程序
}
else
{
switch (number)
{
case 1:
Console.WriteLine("您的餘額為:100000");
break;
case 2:
Console.Write("請輸入提款金額:");
int money_number1 = int.Parse(Console.ReadLine());
break;
case 3:
Console.Write("請輸入轉帳帳號:");
int bank;
bool bank_good = int.TryParse(Console.ReadLine(), out bank);
if (bank_good != true)
{
Console.WriteLine("無此帳號");
System.Environment.Exit(0); // 終止所有程序
break;
}
else
{
Console.Write("請輸入轉帳金額:");
int money_number2 = int.Parse(Console.ReadLine());
break;
}

case 4:
Console.Write("請輸入存款金額:");
int money_number3 = int.Parse(Console.ReadLine());
break;
}
}
}
else
{
Console.WriteLine("輸入帳號或密碼不正確");
System.Environment.Exit(0); // 終止所有程序
}

while 迴圈

資料參考專案 Learning 09。

操作說明

讓數值從 0 開始,每次增加 10,直到 500;先確認條件是否包含最後一個值。
註:【number++;】等於【number+=1;】等於【number = number + 1;】

  1. 方法一:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    int number1 = 0;
    while (true)
    {
    Console.WriteLine(number1);
    if (number1 == 500)
    {
    Console.WriteLine(number1);
    break; // 跳出while
    }
    number1 += 10; // number1 = number1 + 10;
    }
  2. 方法二:
    1
    2
    3
    4
    5
    6
    int number2 = 0;
    while (number2 <= 500)
    {
    Console.WriteLine(number2);
    number2 += 10;
    }

do while 迴圈

資料參考專案 Learning 10。

操作說明

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int number;  // 宣告區域變數

// do while 先執行,後判斷
do // 執行
{
Console.Write("請輸入成績:");
bool pass = int.TryParse(Console.ReadLine(), out number);
if ((pass && number <= 100) != true) // 輸入數字以外的文字,且大於100分,就顯示輸入錯誤
{
Console.WriteLine("輸入錯誤");
}
if ((number >= 60) != true)
{
Console.WriteLine("成績不及格,繼續補考!");
}
else
{
Console.WriteLine("成績及格了!");
}
}
while (number>60); // 設定條件值關閉while迴圈

for 迴圈

資料參考專案 Learning 11。

操作說明

1
2
3
4
5
// for(變量宣告;變量條件;變量增量)
for (int i = 0; i <= 100; i += 5)
{
Console.WriteLine($"數字:{i}");
}

迴圈運算的九九乘法表

資料參考專案 Learning 12。

操作說明

九九乘法表可用巢狀迴圈處理:外層決定其中一個乘數,內層逐一列出另一個乘數,再安排換行。

1
2
3
4
5
6
7
8
9
1x1=1
1x2=2 2x2=4
1x3=3 2x3=6 3x3=9
1x4=4 2x4=8 3x4=12 4x4=16
1x5=5 2x5=10 3x5=15 4x5=20 5x5=25
1x6=6 2x6=12 3x6=18 4x6=24 5x6=30 6x6=36
1x7=7 2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49
1x8=8 2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64
1x9=9 2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81
  • 程式碼:
    1
    2
    3
    4
    5
    6
    7
    8
    for (int x = 1; x <= 9; x += 1) 
    {
    for (int y = 1; y <= x; y += 1)
    {
    Console.Write($"{y}x{x}=" + (x * y)+"\t"); // 【"\t"】段落對齊
    }
    Console.WriteLine();
    }

陣列的理解與使用

陣列把同型別的多個值放在一起,索引從 0 開始。宣告大小後,要留意最後一個有效索引是長度減 1。

資料參考專案 Learning 13。

操作說明

  1. 方式一:
    1
    2
    3
    4
    5
    string[]names = new string[3]; //宣布數組的數量,創建一組字符串內存空間
    names[0] = "編號一";
    names[1] = "編號二";
    names[2] = "編號三";
    Console.WriteLine(names[0]+"\t"+ names[1] + "\t" + names[2]);
  2. 方式二:
    1
    2
    3
    string[] numbers = new string { "數字一", "數字二", "數字三" }; // new初始化
    //string[] numbers = { "數字一", "數字二", "數字三" };
    Console.WriteLine(numbers[0] + "\t" + numbers[1] + "\t" + numbers[2]);

“指定”類別的使用方式

Student 範例把資料與行為放進類別。原文的「靜態特徵」指屬性資料、「動態特徵」指方法行為,並不等同於 C# 的 static 關鍵字。

資料參考專案 Learning 14。

操作說明

類別

在該專案裡面,按Ctrl + Shift + A,即可跳出新增項目的視窗。
類別:原文圖片 04

  1. 類別名稱建立為Student.cs。
  2. class Student{}更改為public class Student{}
  3. 靜態特徵:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    #region 靜態特徵
    /// <summary>
    /// 學生姓名
    /// </summary>
    public string Name;
    /// <summary>
    /// 年齡
    /// </summary>
    public int Age;
    /// <summary>
    /// 性別
    /// </summary>
    public char Sex;
    /// <summary>
    /// 電話
    /// </summary>
    public string Phone;
    #endregion
  4. 動態特徵:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    #region 動態特徵
    /// <summary>
    /// 學習
    /// </summary>
    public void Learn()
    {
    Console.WriteLine(this.Name + "\t" + "正在看書學習..."); // this.Name 當前名稱.姓名
    }
    #endregion

Program 主程式

  1. 索引關聯資料建立:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    Student stu_1 = new Student();
    stu_1.Name = "標號一";
    stu_1.Age = 18;
    stu_1.Sex = '女';
    stu_1.Phone = "0987878787";

    Student stu_2 = new Student();
    stu_2.Name = "標號二";
    stu_2.Age = 19;
    stu_2.Sex = '女';
    stu_2.Phone = "0978787878";

    Student stu_3 = new Student();
    stu_3.Name = "標號二";
    stu_3.Age = 20;
    stu_3.Sex = '男';
    stu_3.Phone = "0969696969";
  2. 主要程式:
    1
    2
    3
    4
    5
    6
    7
    8
    Student[] stu = { stu_1, stu_2, stu_3 }; // 占位符的使用
    for (int i = 0; i < stu.Length; i += 1) // stu.Length 是 stu 的長度。
    {
    // 靜態特徵
    Console.WriteLine($"姓名:{stu[i].Name} 性別:{stu[i].Sex} 年紀:{stu[i].Age} 電話號碼:{stu[i].Phone}");
    // 動態特徵
    stu[i].Learn();
    }

呼叫類別的方法

資料參考專案 Learning 15。

操作說明

類別

在該專案裡面,按Ctrl + Shift + A,即可跳出新增項目的視窗。
類別:原文圖片 05

  1. 類別名稱建立為Dog.cs。
  2. class Dog{}更改為public class Dog{}
  3. 靜態特徵:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    #region 靜態特徵
    /// <summary>
    /// 玩具名稱
    /// </summary>
    public string name;

    /// <summary>
    /// 玩具顏色
    /// </summary>
    public string color;
    #endregion
  4. 動態特徵:
    存取硬體有可能會報錯,應依方法的回傳型態與錯誤處理方式設計;不是所有方法都需要回傳值。
    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
    /// <summary>
    /// string_Run
    /// </summary>
    /// <returns></returns>
    public string Run_string()
    {
    Console.WriteLine($"{this.name}的{this.color}真難看~");

    return "abc"; // 回傳值
    }

    /// <summary>
    /// int_Run
    /// </summary>
    /// <returns></returns>
    public int Run_int()
    {
    Console.WriteLine($"{this.name}的{this.color}真難看~");

    return 1; // 回傳值
    }

    /// <summary>
    /// bool_Run
    /// </summary>
    /// <returns></returns>
    public bool Run_bool()
    {
    Console.WriteLine($"{this.name}的{this.color}真難看~");

    return true; // 回傳值
    }

Program 主程式

  1. 索引關聯資料建立:
    1
    2
    3
    4
    // 資料關聯建立
    Dog dog1 = new Dog();
    dog1.name = "醜八怪";
    dog1.color = "黃色";
  2. 呼叫類別的”動態特徵”執行:
    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
    // string
    #region string_Run
    string result_string = dog1.Run_string(); // 調用類別的"動態特徵"執行

    if (result_string =="abc")
    {
    Console.WriteLine("string調用成功");
    }
    else
    {
    Console.WriteLine("string調用失敗");
    }
    #endregion


    // int
    #region int_Run
    int result_int = dog1.Run_int(); // 調用類別的"動態特徵"執行

    if (result_int == 1)
    {
    Console.WriteLine("int調用成功");
    }
    else
    {
    Console.WriteLine("int調用失敗");
    }
    #endregion


    // bool
    #region bool_Run
    bool result_bool = dog1.Run_bool(); // 調用類別的"動態特徵"執行

    if (result_bool == true)
    {
    Console.WriteLine("bool調用成功");
    }
    else
    {
    Console.WriteLine("bool調用失敗");
    }
    #endregion

帶參數的動態特徵

資料參考專案 Learning 16。

操作說明

非帶參數

類別

在該專案裡面,按Ctrl + Shift + A,即可跳出新增項目的視窗。
類別:原文圖片 06

  1. 類別名稱建立為Lamp.cs。
  2. class Lamp{}更改為public class Lamp{}
  3. 程式碼:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    public void Open()
    {
    Console.WriteLine("開燈");
    }

    public void Close()
    {
    Console.WriteLine("關燈");
    }
Program 主程式
  • 程式碼:
    1
    2
    3
    Lamp lamp = new Lamp(); 
    lamp.Open();
    lamp.Close();

帶參數

類別

在該專案裡面,按Ctrl + Shift + A,即可跳出新增項目的視窗。
類別:原文圖片 07

  1. 類別名稱建立為PPAP.cs。
  2. class PPAP{}更改為public class PPAP{}
  3. 程式碼:
    1
    2
    3
    4
    5
    public string ppap(string fruit)
    {
    string result = fruit + "Pen";
    return result; // 回傳值
    }
Program 主程式
  • 程式碼:
    1
    2
    3
    PPAP PPAP = new PPAP();
    string result = PPAP.ppap("Apple");
    Console.WriteLine($"{result}");

流程控制關鍵詞

break 離開目前迴圈或 switch;continue 略過本次迭代剩餘部分;return 結束目前方法,並依回傳型態決定是否帶回值。請配合各例的呼叫位置閱讀。

資料參考專案 Learning 17。

操作說明

  • 流程控制關鍵詞
    1
    2
    3
    break;      // 終止,結束之意
    continue; // 繼續,效率之意
    return; // 返回,傳遞之意

範例解釋

1. break 終止
  • switch
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    Console.Write("請輸入number值:");
    int number = int.Parse(Console.ReadLine());
    switch (number)
    {
    case 1:
    Console.WriteLine("數字一");
    break;

    default: // 默認
    Console.WriteLine("沒有東西");
    break; // 終止
    }
  • for
    1
    2
    3
    4
    5
    6
    7
    8
    for (int n = 1; n < 100; n += 1)
    {
    if (n % 2 == 0)
    {
    Console.WriteLine($"第一個偶數: {n}");
    break;
    }
    }
  • while
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    int m = 0;
    while (m < 20)
    {
    Console.WriteLine($"m: {m}");
    if (m == 10)
    {
    break; // 到m=10時,跳脫while迴圈。
    }
    m += 2;
    }
2. continue 繼續
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int sum = 0;
for (int i = 1; i < 10; i += 1)
{
if (i % 2 == 0)
{
sum += i;
continue; // 循環繼續,效率更高。
/* 【i】的結果:
加入continue:1、3、5、7、9
取消continue:1、2、3、4、5、6、7、8、9
*/
}
Console.WriteLine($"我來亂的{i}");
}
Console.WriteLine($"sum :{sum}");
3. return 返回
1
2
3
4
5
6
7
8
9
10
11
12
13
static void Main(string[] args)
{
string str = Test();
Console.WriteLine(str);
}

/// <summary>
/// return 返回,測試
/// </summary>
public static string Test()
{
return "這是一個return 的字串";
}

存取修飾符

修飾詞決定哪些程式碼可以使用型別或成員。internal 的邊界是組件,而不是命名空間;同名命名空間不表示一定有權限存取。

操作說明

存取權限

  1. private:私有的,僅類的內部程式可以使用
  2. protected:受保護的,類的內部和繼承子類可以存取。
  3. internal:內部的,可由同一個組件(assembly)中的程式碼存取。
  4. public:公共的,完全公開,沒有存取限制。

練習時先改變一個條件,再觀察編譯訊息或執行路徑,會比只記名稱更容易理解。

VS除錯Bug的方法

先在條件判斷前設斷點,查看變數,再用 F10 或 F11 追蹤下一步。預測哪一個分支會執行,再與除錯結果對照。

  • 三種常用的除錯操作
  1. F5:啟動或繼續執行,直到遇到斷點或程式結束。
    斷點方式:在VS 2019中,點選程式行左側的邊界,或使用 F9 切換斷點;紅色圓點表示斷點已設置。
  2. F10:逐程序執行(Step Over),通常不進入呼叫的方法。
  3. F11:逐步執行(Step Into),可進入呼叫的方法。

練習時先改變一個條件,再觀察編譯訊息或執行路徑,會比只記名稱更容易理解。

參考型別與實值型別

資料參考專案 Learning 18。

操作說明

整數型別的特性

值類型
  • C# 支援下列預先定義的整數型別:
    C# 型別/關鍵字 範圍 大小 .NET 類型
    sbyte -128 到 127 帶正負號的 8 位元整數 System.SByte
    byte 0 至 255 不帶正負號的 8 位元整數 System.Byte
    short -32,768 至 32,767 帶正負號的 16 位元整數 System.Int16
    ushort 0 到 65,535 不帶正負號的 16 位元整數 System.UInt16
    int -2,147,483,648 至 2,147,483,647 帶正負號的 32 位元整數 System.Int32
    uint 0 到 4,294,967,295 不帶正負號的 32 位元整數 System.UInt32
    long -9,223,372,036,854,775,808 至 9,223,372,036,854,775,807 帶正負號的 64 位元整數 System.Int64
    ulong 0 到 18,446,744,073,709,551,615 不帶正負號的 64 位元整數 System.UInt64
自訂實值型別可使用 struct 與 enum;內建整數、浮點數等也屬於實值型別。
  1. struct
    您使用 struct 關鍵字來建立您自己自訂的實值型別。 一般來說,會使用結構做為一小組相關變數的容器,如下列範例所示︰

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    public struct Coords
    {
    public int x, y;

    public Coords(int p1, int p2)
    {
    x = p1;
    y = p2;
    }
    }
  2. enum

  • 列舉型態(或列舉類型)是由基礎整數型別的一組命名常量定義的值類型。 要定義的列舉類型,請使用enum 關鍵字並指定列舉成員的名稱:

    1
    2
    3
    4
    5
    6
    7
    enum Season
    {
    Spring,
    Summer,
    Autumn,
    Winter
    }
  • 預設情況下,列舉成員的關聯常量值為int類型 ;它們以零開始,然後按照定義文本順序增加一個。您可以明確指定任何其他整數型別作為列舉類型的基礎類型。 您還可以明確指定關聯的常量值,如以下範例所示:

    1
    2
    3
    4
    5
    6
    7
    enum ErrorCode : ushort
    {
    None = 0,
    Unknown = 1,
    ConnectionLost = 100,
    OutlierReading = 200
    }

參考文章

  1. Microsoft C# 程式設計手冊( 文章連結)

建議的練習順序

先完成輸入輸出與變數,再練習判斷、迴圈及陣列,最後用類別整理資料和方法。每個 Learning 專案先單獨執行,確認輸入與預期輸出,再加入自己的修改。

參考:C# 加法與字串串接、internal 的存取範圍。