# C#程式筆記 在這當中集合到了我上課的筆記、以及在家學習、在培訓時期所學到的許多知識 許多不會的都是從網上搜尋、YT或ChatGPT請教而來,現在的科技發達真是對人們幫助挺大 > [name=anna0212] ## 目錄: > [TOC] ## 主控制台 (.NET) console皆為主控制台的寫法,其餘輸出語法Form也可使用 ### 輸入 ```csharp= Console.ReadLine(); //string類型 Console.Read(); //int類型 ``` 等待使用者按下任意鍵後結束 通常可以放在最後,不讓表單直接結束 ```csharp= Console.ReadKey(); ``` ### 輸出 ```csharp= Console.WriteLine(); //會換行 Console.Write(); //不會換行 ``` ### 顏色改變 ```csharp= Console.BackgroundColor = ConsoleColor.DarkBlue; // 設置背景顏色 Console.ForegroundColor = ConsoleColor.White; // 設置文字顏色 Console.WriteLine("Text with Dark Blue background and White text"); Console.ResetColor(); // 恢復預設顏色 ``` ### 格式 #### 字符 * \r:回車,將光標移到當前行的開頭 寫到中間的時候,你想擦掉從開頭到中間的部分,然後重新寫:就像「把鉛筆移回紙的開頭,準備重新寫」,而不是跳到下一行。 ``` 12345678 1213 171819 //中間的部分開始就是回車 ``` * \n:換行,將光標移到下一行。 * \t:對齊文字 ```csharp= Console.WriteLine("Name\tAge\tCity"); //輸出:Name Age City Console.WriteLine("Anna\t25\tTaipei"); // Anna 25 Taipei ``` * \\":雙引號 * \\\:反斜杠 #### 字符串插值 ```csharp= int i = 1; int j = 1; Console.WriteLine("%d*%d\n", i, j); Console.WriteLine($"{ i }*{ j }"); ``` ### 補齊工具 * {0:00}: 補0工具 ```csharp= ("{0:00}",5); == $"{5:00}"; //輸出: 05 ("{0:000}", 7); // 輸出: 007 ("{0:0.00}", 7.1)); // 輸出: 7.10 ``` * 補任何符號的工具: ```csharp= //**PadLeft(補到多少長度,用甚麼補):向右補到相對應的字串長度 Label1.text = "melcome".PadLeft(10,'*'); //輸出:***welcome //字串長度為10 //**PadRight(補到多少長度,用甚麼補):向左補到相對應的字串長度 Label1.text = "melcome you".PadRight(15,'@'); //輸出:welcome you@@@@ //字串長度為15 ``` ## 一些物件設定 許多物件的某些設定的程式碼皆是相同的,在這裡我整理出來幾個我用到或常用的 在這裡我用pictureBox來進行示範,可以改成其他的如:button、Label ### 定位 表單左上為(0,0) left : 0、top : 0 ```csharp= pictureBox1.Location = new Point(left,top); ``` ### 改變位置 ```csharp= pictureBox.left +=10 //向右 pictureBox.top -=10 //向上 ``` ### 顯示、隱藏 Image為圖片、Visible為顯示 ```csharp= pictureBox.Image=false; //一開始看不到 pictureBox.Visible=false; ``` ### 建立分身 (新的物件) 在程式碼當中生成新的物件,可以在許多遊戲中出現 存入控制項集合當中才會顯示 ```csharp= PictureBox newPictureBox = new PictureBox(); this.Controls.Add(newPictureBox); // 將分身加入到表單的控制項集合中 ``` ### Controls 控制項集合 通過這個集合來新增、移除或存取子控件。 ```csharp= Button btn = new Button(); btn.Text = "Click Me"; btn.Location = new Point(50, 50); this.Controls.Add(btn); // 將按鈕添加到表單中 this.Controls.Remove(btn); // 從表單中移除按鈕 btn.Dispose(); // 釋放資源 this.Controls.Clear(); // 清空表單中的所有子控件 ``` ### Rectangle 是否碰撞 獲取兩個 PictureBox 的範圍矩形 ```csharp= Rectangle rect1 = pictureBox1.Bounds; Rectangle rect2 = pictureBox2.Bounds; ``` 判斷是否碰撞 ```csharp= if (rect1.IntersectsWith(rect2)) { MessageBox.Show("兩個物件發生碰撞!"); } else { MessageBox.Show("沒有碰撞。"); } ``` ### 顏色顯示 數值為0~225 ```csharp= r=225; g=0; b=0; label1.BackColor=Color.FromArgb(r,g,b); ``` ### 開啟圖片 先將圖片存於檔案Debug當中 ```csharp= pictureBox1.Image = new Bitmap("檔案名.gif"); ``` 先將圖片存於PictureBox圖片當中 ```csharp= newPictureBox.Image = Properties.Resources.Flappy_Bird_down; ``` 圖片清空 ```csharp= pictureBox1.Image=null; ``` ImageList ```csharp= int currentIndex = 0; // 切換到下一張圖片 currentIndex = (currentIndex + 1) % imageList1.Images.Count; pictureBox1.Image = imageList1.Images[currentIndex]; ``` ### MessageBox 必須正確的參數順序來使用 先是內容>標題>按鈕>圖片 ```csharp= MessageBox.Show("文字", "標題", MessageBoxButtons.OK, MessageBoxIcon.Warning); //**MessageBoxButtons:用來指定對話框中顯示的按鈕類型(如 YesNo、OKCancel 等)。 //**MessageBoxIcon:用來指定對話框中顯示的圖標類型(如 Information、Warning、Error 等)。 ``` 如何判斷使用者按下何者按鈕: ```csharp= DialogResult result = MessageBox.Show(.... if (result == DialogResult.Yes) {.... ``` ### InputBox 彈出一個輸入對話框,讓使用者輸入文字 ```csharp= string result = Interaction.InputBox("請輸入您的名字:", "輸入框標題", "預設值"); Console.WriteLine("使用者輸入:" + result); ``` 如果想要多筆資料輸入:用 vbCrLf 允許換行 ```csharp= string input = Microsoft.VisualBasic.Interaction.InputBox("請輸入多筆資料 (用 Enter 分隔)", "輸入資料", "第一行" + Environment.NewLine + "第二行"); string[] data = input.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); foreach (string item in data) { Console.WriteLine(item); } ``` ### 開啟檔案(網址) * 先存入Debug檔案中: ```csharp= Process.Start("檔案名.檔案類型"); ``` 如果是想執行一個C#檔案.exe,記得得將另一個檔案從din\Debug所有檔案,複製去執行程式的din\Debug檔案裡 * 檔案路徑方式: ```csharp= string filePath = @"C:\example\file.pdf"; Process.Start(filePath); ``` ```csharp= System.Diagnostics.Process.Start("explorer.exe", @"C:\你的資料夾路徑"); System.Diagnostics.Process.Start("https://hackmd.io/@anna0212/S1C7_W2rJx"); ``` ### TabPage物件 * 隱藏或顯示 需要手動新增或移除 TabPage 👉 方法 1:移除 tabPage2 ```csharp= tabControl1.TabPages.Remove(tabPage2); ``` 👉 方法 2:用變數記住 tabPage2(之後可恢復) ```csharp= TabPage hiddenTab = tabPage2; // 記住 tabPage2 tabControl1.TabPages.Remove(tabPage2); ``` 👉 方法 1:重新加入 tabPage2 ```csharp= tabControl1.TabPages.Add(tabPage2); ``` 👉 方法 2:用變數恢復 tabPage2 ```csharp= tabControl1.TabPages.Add(hiddenTab); ``` ## 事件 事件是在表單、物件屬性裡,有一個紅色閃電 在這當中有許多的功能十分好用 ### 檢測是否按下鍵盤按鍵 先點擊事件Form1_KeyDown * 是否按下了空白鍵 ```csharp= if (e.KeyCode == Keys.Space) // 其他按鍵:Keys.W { MessageBox.Show("你按下了空白鍵!"); } ``` * UpArrow // ↑ 上 * DownArrow // ↓ 下 * ILeftArrow // ← 左 * RightArrow // → 右 ### 檢測滑鼠是否按下 先點擊事件Form1_MouseDown * 是否按下左鍵 ```csharp= if (e.Button == MouseButtons.Left) { MessageBox.Show("你按下了滑鼠左鍵!"); } ``` * 是否按下右鍵 ```csharp= if(e.Button == MouseButtons.Right) { MessageBox.Show("你按下了滑鼠右鍵!"); } ``` ### 檢測滑鼠是否移動 先點擊事件Form1_MouseMove * 透過滑鼠移動控制PictureBox ```csharp= private void Form1_MouseMove(object sender, MouseEventArgs e) { pictureBox1.Image=imageList1.Images[0]; if (drag) { pictureBox1.Left = e.X - 50; pictureBox1.Top = e.Y - 50; } } ``` ## Form1表單設定 Form1表單有很多功能,在他的事件裡面更是有大精彩 如:判斷是否按下按鍵、滑鼠的移動 ### 關閉、退出表單 先關閉主選單視窗 ```csharp= this.Close(); ``` 完全退出應用程式 ```csharp= Application.Exit(); ``` 隱藏 ```csharp= this.Hide(); // 隱藏登入視窗 ``` ### 回到開始時的介面 ```csharp= Form1_Load(null, null); Form1_Load(sender, e); ``` ### 其他、個類屬性 ``` Manual:手動設定位置,需要搭配 Location 屬性。 CenterScreen:將視窗置於螢幕中央。 WindowsDefaultLocation:讓 Windows 作業系統決定視窗位置。 CenterParent:將視窗置於父視窗的中央(適合子視窗)。 WindowsDefaultBounds:讓 Windows 作業系統決定視窗的大小和位置。 ``` ### Program.cs ![螢幕擷取畫面 2025-01-01 234724](https://hackmd.io/_uploads/HJFZV1m8ke.png=) 調整成按下開始時執行start專案 ````csharp= Application.Run(new Start()); ```` ### 建立第二個表單 可能偶爾會需要按下Botton時可以開啟另一個表單,除了把先製作好的C#檔案放入Debug開啟外,還可以在同一個C#檔案中製作 #### 如何建立 ![螢幕擷取畫面 2025-01-01 222639](https://hackmd.io/_uploads/H1-KE1mIke.png=) #### 如何開啟 * 方法一: * 這就是直接的顯示出來 ```csharp= Form2 form2 = new Form2(); form1.Show(); ``` * 方法二: 開啟第二個表單時,第一個表單不能使用,直到第二個表單結束後,第一個才會繼續開始運行,這樣就少了許多bug。 ```csharp= Form2 form2 = new Form2(); form1.ShowDialog(); ``` #### 呼叫其他視窗(Form2)的變數 想要呼叫 Start 類別中的靜態變數 num: ```csharp= //靜態變數: public static int x; Start.num = 0; // 直接用類別名稱 Start 來訪問靜態變數 ```` 實例變數的呼叫: ```csharp= 實例變數: int x; Start www = new Start(); www.num = 0; // 如果 num 是實例變數,這樣才是正確的 ``` ## Random 亂數 在一定範圍內隨機取數 1~100 -------> 57 要注意(min,max)的寫法,(1,101)max會減1 ```csharp= Random random = new Random(); int randomInt = random.Next(min,max); ``` ## For/While/Do...while 迴圈 滿足t<=5(條件)則執行程式 ### * For 1. int t=0;只在一開始進入時執行,他是設定這個迴圈的初始值 2. 然後進行t是否小於等於5的條件判斷 3. 條件成立>執行程式 4. 程式執行完便回來進行t++(t+1) 5. 回到 2.如此進行 ```csharp= For(int t=0 ; t<=5 ; t++){ } ``` ### * While 判斷條件是否繼續執行,成立就執行程式碼 ```csharp= While(t<=5){ } ``` ### * Do...while 先執行do迴圈當中的程式,然後判斷條件是否繼續執行 ```csharp= Do{ }while(t<=5); //要分號! ``` Continue:回到條件判斷 Break:跳出迴圈 ```csharp= For(條件) { 敘述區段; Continue; } ``` ## Foreach * 概念介紹: 類似於將一串資料依序找出 資料可能為string也可能為Array、list 由前至後的選取資料輸出 ```csharp= foreach (資料型別 變數名 in 集合) { // 在這裡使用變數 } ``` * 範例: ```csharp= int[] numbers = { 1, 2, 3, 4, 5 }; foreach (int num in numbers) { Console.WriteLine(num); // 輸出陣列內的數字 } ``` 輸出: 1 2 3 4 5 >ChatGPT提供 ## Sleep 等待、暫停 1000為一秒 ```csharp= Sleep(100); Thread.Sleep(100); //等待0.1秒 ``` ## DateTime 時間 ```csharp= DateTime formatted = DateTime.Now; //現在時間 string formatted = now.ToString("yyyy-MM-dd HH:mm:ss.fffffff zzz"); DateTime startDate = new DateTime(2025, 3, 15); DateTime week2 = new DateTime(dt1.Year, dt1.Month, 1);//同一個月的一號 string formattedDate = now.ToString("yyyy-MM-dd"); int year = now.Year; // 年 int month = now.Month; // 月 int day = now.Day; // 日 int hour = now.Hour; // 小時 int minute = now.Minute; // 分 int second = now.Second; // 秒 AddDays 的結果要重新指派,需要用 now = now.AddDays(1) //增加一天 (星期、月分都會跟著變) int day = Math.Abs((dt2 - dt1).Days); //4/1 減 3/30可能會出錯,需要搭判Math DateTime today = DateTime.Today; DayOfWeek dayOfWeek = today.DayOfWeek; Console.WriteLine(dayOfWeek); // 例如 "Monday"星期幾(從 0 到 6 分別代表星期天到星期六) ``` * yyyy-MM-dd → 年-月-日 * HH:mm:ss → 小時:分鐘:秒 * .fffffff → 7 位數的毫秒(精確到 100ns) * zzz → 時區偏移量(-07:00 表示 UTC-7) ## Dictionary 儲存資料 它很類似一個兩格式的表單,儲存資料。要注意到Key規則比較多!! 不允許直接修改 Key,但你可以修改 Value。 * Key:唯一的標識,用來快速查找值。 鍵的型別(例如 int、string 等)。{不可以重複!!!} * Value:與鍵對應的資料,可以是任意型別。 值的型別(可以是任何類型)。 |Key | Value | | -------- | -------- | | 1 | 王曉明 | |2 |王大明 ### 宣告 ```csharp= Dictionary<keyType, valueType> 名稱 = new Dictionary<keyType, valueType>(); // 創建一個 Dictionary,Key 是 int,Value 是 string Dictionary<int, string> students = new Dictionary<int, string>(); ``` ### 加入、刪除、清空 ```csharp= var students = new Dictionary<int, string> { { 1, "Alice" }, { 2, "Bob" }, { 3, "Charlie" } }; students[2] = "Bobby"; // 修改 Key=2 的值 dictionary.Add(key, value); //添加資料 dictionary.Remove(key); // 刪除指定鍵的鍵值對 dictionary.Clear(); // 清空字典 ``` ### 其他 ```csharp= dictionary.ContainsKey(key); // 檢查鍵是否存在 dictionary.ContainsValue(value); // 檢查值是否存在 dictionary.Count; // 返回字典中的鍵值對數量 ``` ## Math 計算 ```csharp= Math.Pow(a,0.5) // 次方 a的0.5次方=開根號 Math.Min(Math.Min(num1, num2), num3) // 最小值 Math.Abs():取得絕對值。 Math.Sqrt():計算平方根。 Math.Ceiling():將數值無條件進位。 Math.Floor():將數值無條件捨去。 Math.Round():將數值四捨五入。 ``` ## Replac、Remove 改變字串 Replac刪除或改變字串的某個部分,可能將a替換成b、刪除*等等 Remove刪除第幾個字如此 | 方法 | 功能 | |-------------------------|------------------| | Replace("舊字串", "新字串") | 替換字串內容 | | Replace("字元", "") | 刪除特定字元 | | Remove(索引, 長度) | 刪除特定範圍的內容 | ### Replac ```csharp= Console.WriteLine("Hello, World!"Replace(",", "")); //輸出Hello World! ``` ### Remove ```csharp= Console.WriteLine("Hello, World!".Remove(5, 1);); //輸出Hello World! ``` ## Try/catch 檢視Bug Try { } carth { } try中的{ 程式碼 }Bug錯誤,則執行carth中的{ 程式碼 },carth{return}可讓程式回去執行一次 * 小技巧: 可以在變數的屬性轉換中用到 ```csharp= int old1; Console.WriteLine("年齡"); try { old1 = int.Parse(Console.ReadLine()); Console.WriteLine(old1 + " old."); } catch { Console.WriteLine("輸入錯誤!"); } ``` * catch (FormatException) 如果輸入的內容不是有效的整數,拋出 FormatException,並顯示錯誤訊息 * catch (Exception ex) 捕捉所有其他可能的異常,顯示錯誤訊息 ## If/else 如果...那麼... If(條件) {達成執行} 不達成>> else if(條件) {達成執行} 不達成>> eles{達成執行} ![If(條件) 1 of 1](https://hackmd.io/_uploads/By3f1cGLye.png=) ```csharp= Console.WriteLine("請輸入一個數字:"); string input = Console.ReadLine(); // 讀取使用者輸入 int number; if (int.TryParse(input, out number)) // 檢查輸入是否為有效的整數 { if (number > 0) { Console.WriteLine("你輸入的是一個正數。"); } else if (number < 0) { Console.WriteLine("你輸入的是一個負數。"); } else { Console.WriteLine("你輸入的是零。"); } } else { Console.WriteLine("輸入無效,請輸入一個有效的整數。"); } ``` >ChatGPT提供範例 ### 判斷語法 * 等於 == * 大於等於 >= * 小於等於 <= * 小於 < * 大於 > * 或 || * 且 && ### 三元運算子 等價於 if-else,但更簡潔 ```csharp= 條件判斷 ? 條件為 true 時執行的值 : 條件為 false 時執行的值; 範例: int age = 18; string status = (age >= 18) ? "成人" : "未成年"; Console.WriteLine(status); // 輸出:成人 bool card_trorfa; ❌answ % 10 == 0 ? card_trorfa = true : card_trorfa = false; //運算式(expression),必須要有 返回值。 ✔️card_trorfa = answ % 10 == 0; ``` ## Switch/case Switch(條件運算源頭) { case(條件等於): 執行程式; Break; // 結束以內的程式 Default: // 都沒有相等的則執行以下程式 執行程式; Break; ```csharp= Console.WriteLine("請選擇一個選項:"); Console.WriteLine("1. 顯示問候語"); Console.WriteLine("2. 顯示當前日期"); Console.WriteLine("3. 離開程式"); string input = Console.ReadLine(); // 讀取使用者輸入 switch (input) { case "1": Console.WriteLine("Hello! 祝你有美好的一天!"); break; case "2": Console.WriteLine($"今天的日期是{DateTime.Now.ToShortDateString()}"); break; case "3": Console.WriteLine("程式結束,謝謝使用!"); break; default: Console.WriteLine("無效選項,請輸入 1、2 或 3。"); break; } ``` 如果要寫多少到多少,就需要使用到when ```csharp= switch (x) { case int n when (n >= 5 && n <= 20): // x 在 5 到 20 之間時執行 break; default: // 其他情況 break; } ``` 多種寫法: ```csharp= string gender = reader["Gender"].ToString() switch { "1" => "男", "2" => "女", "3" => "其他", _ => "未知" }; ``` >ChatGPT提供範例 ## List 皆為從0開始載入數值,加入五個數字進去為:0,1,2,3,4 ,總共五個 * 設定: ```csharp= List<int> numbers = new List<int> { 5, 2, 8, 1, 4 }; numbers.Sort(); // 對數字進行排序,輸出: 1, 2, 4, 5, 8 List<string> fruits = new List<string> { "Banana", "Apple", "Cherry" }; fruits.Sort(); // 對字符串進行排序,輸出: Apple, Banana, Cherry ``` * 刪除數據: ```csharp= numbers.Remove(53); // 為53的數值 numbers.RemoveAt(0); // 第一個 ``` * 加入數據: ```csharp= numbers.Add(1); //加入數據到末尾 numbers.Insert(2, 25); // 將數值 25 插入到索引 2 的位置 ``` * 其他: ```csharp= list.Sort(); // 由小到大排序 list.Reverse(); //反轉排序 list.Max(); //獲得最大值(反之) list = list.Distinct().ToList(); //去重複數值結果,要接回 array bool hasNumber = numbers.Contains(3); :檢查列表中是否包含數字 numbers.Clear();:清空列表 IndexOf:查找元素在列表中的索引 Insert:在指定索引位置插入元素。 Reverse:反轉列表中的元素順序。 listBox1.Items.Count、list.Count:取得清單長度。 ``` ## Array 陣列 皆為從0開始載入數值 與List不同,此為固定的大小,設定5個則為5個 ### * 一維陣列 1. 方法一: ```csharp= string[] score = new string[5] {"國文", "英文", "數學", "生物", "理化" }; ``` 2. 方法二: ✅ 優點:可以放任何型別(但會自動裝箱成 object) ❌ 缺點:效率差、沒有類型安全 ```csharp= ArrayList score = new ArrayList(); ``` ### * 二維陣列: 為一個很抽象的東西,他像是一個表單的樣子,有行與列 如此的一個陣列:第一行第一列為5、第二行第三列為7 ```csharp= int[,] score = new int[3,4]; // 3 行 4 列的二維陣列 array[0, 0] = 1; // 設定第一個元素為 1 int[,] array = { //輸出 1 2 3 4 { 1, 2, 3, 4 }, 5 6 7 8 { 5, 6, 7, 8 }, 9 10 11 12 { 9, 10, 11, 12 } }; array[2, 1] = 10; // 將第 3 行第 2 列的元素修改為 10 int rows = matrix.GetLength(0); // 獲取行數 int cols = matrix.GetLength(1); // 獲取列數 Console.WriteLine(scores.Length); // 輸出12,3 行 × 4 列 = 12 個元素 ``` ### 其他補充: Split(' ')字串分割方法 一個字串內如果有空白的就切割成多個單字,所以也可以改成','有,的就切割 ```csharp= string text = "Hello World Example"; string[] parts = text.Split(' '); // 以空格分割 輸出: parts[0] = "Hello" parts[1] = "World" parts[2] = "Example" ------------------------------------ int score[3]={50,30,55} Array.Sort(score); //從小排到大 score.Length //陣列長度 ------------------------------------ // rd1 是去重覆結果、然後才去抽牌計算比大小 ArrayList rd1 = new ArrayList(rd.Cast<int>().Distinct().ToList()); //.Distinct(): //{1, 2, 3, 2, 3, 4} → Distinct → {1, 2, 3, 4} ``` ## 變數 如同數學中的x , 存一個東西在其中 基本分為: * bool布林值分為false、ture在判斷中可以用到 * char單字元'A' 或 '4' * string字串 "asdcs548" 或 "嗨搂你好喔" * int,float,double 皆是存取數字的,int 為存整數沒有任何小數或負數,其他的由左至由存取的數字多越多區分 * Tuple來一次裝多個不同型別資料的容器,很類似C++的struct [(點擊查看)](https://hackmd.io/bpvVsufJR5Se0rC3bDqWZQ?view#struct) ```csharp (string name, int age) person = ("小明", 15); Console.WriteLine(person.name); // 小明 Console.WriteLine(person.age); // 15 ``` * 包含「時區」的 DateTimeOffset 值(2021-08-11 16:26:52.6026936 +08:00) 如何更改時區: ```csharp= var taiwan = DateTimeOffset.Now; var utc = taiwan.ToOffset(TimeSpan.Zero); // 轉成 +00:00 var tokyo = taiwan.ToOffset(TimeSpan.FromHours(9)); // 轉 +09:00 ``` * 普通時間DateTime tt(AN/PM)中英文切換 ```csharp= DateTimeOffset now = DateTimeOffset.Now; Console.WriteLine(now.ToString("yyyy-MM-dd hh:mm:ss tt", new CultureInfo("zh-TW"))); // 輸出:2025-07-11 03:45:12 上午 Console.WriteLine(now.ToString("yyyy-MM-dd hh:mm:ss tt", new CultureInfo("en-US"))); // 輸出:2025-07-11 03:45:12 AM --------------------------------------------------------------- DateTime now = DateTime.Now; string tt = now.Hour < 12 ? "AM" : "PM"; label10.Text = "系統時間:" + now.ToString("yyyy-MM-dd hh:mm:ss") + " " + tt; ``` ### 變數設定 變數分為全域變數和區域變數 全域變數顧名思義就是可以在全部地方都可以提取使用 區域變數就是只可以在它設定的那個區域使用(例如label、button當中) * 在Form當中,全域變數是寫在它整個程式大括號當中的,個別寫在label中的是區域變數 ```csharp= 全域變數: namespace 專案名稱 { public partial class Form1 : Form { int an = 0; string haha = "haha"; //全域變數 } } 區域變數: namespace 專案名稱 { public partial class Form1 : Form { private void button1_Click(object sender, EventArgs e) { int a = 0; string hihi = "hihi"; //區域變數 } } } ``` * 在主控制台當中,皆可寫在整個大括號當中,只是全域變數需要加上public static ```csharp= namespace 專案名稱 { internal class Program { public static int an = 0; //全域變數 static void Main(string[] args) { int a = 0; //區域變數 } } } ``` ### 屬性轉換 #### 1. 文字轉數字 ```csharp= int in1; string str1 = "4848"; int1 = int.Parse(str1); ```` #### 2. 數字轉字串 [C#.Tostring(?)](/1hNGAczYRbmNlS_3NG5yYw)在這裡有整理很多 ToString()的括號中可加上: * F1 小數點後一位 * C5 變為貨幣輸出,並取小數到後五位 * D8 00012345 (補足 8 位數) * N2 12,345.00 (千分位 + 兩位小數) * X 3039 (轉 16 進位) * E3 科學記號 (3 位小數)3.142E+00 (3.1415926535) * P1 百分比 (1 位小數)314.2% * yyyy年MM月dd日 (2025年03月10日) ```csharp= int in1=555; string str1 = "4848"; str1 += in1.ToString(); ``` 在變數轉換上時常有出現錯誤的時候 可能你輸入的字串想轉成數字時,裡面卻有文字abc之類的會出現bug,這時就需要一些技巧! #### 3. 單字元轉換: * 去減掉'0'! 要將字元數字 '1'、'3' 轉換為整數 1、3 ```csharp= string inpu1="65482" int digit = inpu1[3] - '0'; ``` * 先改成字串,再改成整數 ```csharp= string intput = "1150603will" intput[1]為char 改成int:int.parse(intput[1].tostring()); ``` ⚠️⚠️⚠️原本的 (cardNumber[0] + cardNumber[1]) 會將兩個 char 轉換為 int 進行 ASCII 碼相加,例如 '4' + '5' = 101。 #### 4. 轉成DateTime 轉成日期可以使用: * DateTime.ParseExact(date, "yyyy年MM月dd日", CultureInfo.InvariantCulture) 如果不是MM月dd日會出bug * DateTime.TryParseExact * DateTime.Parse(較為不嚴謹) 我比較愛用,不然其它太容易出bug * DateTime.TryParse ```csharp= string date = "2025年5月4日" DateTime time = DateTime.Parse(date, CultureInfo.InvariantCulture); ```` CultureInfo.InvariantCulture以防不同地區格式不一的bug * 台灣(中文):2025年04月02日 * 美國(英文):April 2, 2025 * 英國(英文):02/04/2025(日/月/年) * 德國(德文):02.04.2025 ✔️DateTime 相減與 TimeSpan 整理筆記 ```csharp= DateTime start = DateTime.Parse("2025-01-04 12:46:59"); DateTime end = DateTime.Parse("2025-01-04 16:17:21"); TimeSpan diff = end - start; Console.WriteLine($"{diff.Hours} 小時 {diff.Minutes} 分鐘 {diff.Seconds} 秒"); // 輸出:3 小時 30 分鐘 22 秒 ``` 時間的轉換: | 屬性名稱 | 型別 | 說明 | | -------------- | -------- | ------------------------------ | | `TotalDays` | `double` | 總天數(含小數)如 `1.75` 表示 1 天又 18 小時 | | `TotalHours` | `double` | 總小時數(含小數),如 `3.5` 小時 | | `TotalMinutes` | `double` | 總分鐘數(含小數) | | `TotalSeconds` | `double` | 總秒數(含小數) | | `Days` | `int` | 整數天數(不含小數) | | `Hours` | `int` | 差距內的小時(不含天) | | `Minutes` | `int` | 差距內的分鐘(不含小時) | | `Seconds` | `int` | 差距內的秒數(不含分鐘) | | `Milliseconds` | `int` | 毫秒部分 | | `Ticks` | `long` | 奈秒刻度(每秒約 1 千萬 ticks) | #### * 技巧一: int.TryParse是一個布林值,去判斷一個值是否可以轉成int int.TryParse(string ageInput, out int old1) 如果成立,便將string值存入int值內 ```csharp= int old1; Console.WriteLine("年齡"); string ageInput = Console.ReadLine(); if (int.TryParse(ageInput, out old1)) { Console.WriteLine(old1 + " old."); } else { Console.WriteLine("請輸入有效的數字!"); } ``` #### * 技巧二: try{ } catch{ } 當try程式碼中出錯執行catch中的程式碼 ```csharp= int old1; Console.WriteLine("年齡"); try { old1 = int.Parse(Console.ReadLine()); Console.WriteLine(old1 + " old."); } catch { Console.WriteLine("輸入錯誤!"); } ``` ### Convert 靜態類別 轉換屬性 Convert 是一個 **內建的靜態類別**,它提供了 各種不同型別之間的轉換方法,用來將資料從一種型別轉換成另一種。 | 方法名稱 | 功能 | 範例 | | ------------------------- | --------------------- | ---------------------------------- | | `Convert.ToInt32(...)` | 將值轉成 `int`(整數) | `Convert.ToInt32("123")` | | `Convert.ToString(...)` | 將值轉成 `string`(字串) | `Convert.ToString(123)` | | `Convert.ToBoolean(...)` | 將值轉成 `bool`(布林) | `Convert.ToBoolean("true")` | | `Convert.ToDateTime(...)` | 將值轉成 `DateTime`(日期時間) | `Convert.ToDateTime("2024-01-01")` | 🚀 和 int.Parse() 的差別是什麼? ```csharp= int.Parse("123"); // ✅ 可以 int.Parse(null); // ❌ 會丟出例外 int.Parse(DBNull.Value); // ❌ 會丟出例外 -------------------------------------------- Convert.ToInt32("123"); // ✅ 123 Convert.ToInt32(true); // ✅ 1 Convert.ToInt32(null); // ✅ 0 Convert.ToInt32(DBNull.Value); // ✅ 0 ``` ### 呼叫其他視窗(Form2)的變數 想要呼叫 Start 類別中的靜態變數 num: ```csharp= 靜態變數: public static int x; Start.num = 0; // 直接用類別名稱 Start 來訪問靜態變數 ```` 實例變數的呼叫: ```csharp= 實例變數: int x; Start www = new Start(); //Form2表單名稱Start www.num = 0; // 如果 num 是實例變數,這樣才是正確的 ``` ### var 自動判斷 也為變數型態的一種,動推斷變數的類型。 ```csharp= var number = 10; // 自動推斷為 int ``` ### String應用 ```csharp= string input =A1234t49 ; // 讀取輸入的字串 char firstChar = input[0] ; // 第一個字符 intput.length() //文字長度:8 string str = "Hello World"; str = str.Remove(6, 5); //第6個字開始,刪除5個 str.Substring(0, 2) + str.Substring(5); // 取前兩個 + 第五之後 ``` * Split切割 Split(' ')字串分割方法 一個字串內如果有空白的就切割成多個單字,所以也可以改成','有,的就切割 ```csharp= string line = "aaa|bbb"; char ch_line.Split('|')[0] = "aaa"; //以|為切割標準,將aaa和bbb分為兩個陣列 ``` * Replace替換 Replace("-" , "|"); 他會將字串內含有-的部分替換成| ```csharp= string line = "aaa-bbb"; string[] l_line = line.Replace("-" , "|"); //輸出:"aaa|bbb" ``` ## IsLetterOrDigit判斷字母、數字 字母:char.IsLetter(char c) 數字:char.IsDigit(char c) | 方法 | 作用 | 範例 | | ----------------------------- | ------------------------------ | ---------------------------------- | | char.IsDigit('a') | 判斷單一字元是否為數字 | '5' → ✅ true , 'A' → ❌ false | | char.IsLetter('a') | 判斷單一字元是否為英文字母 | 'A' → ✅ true , '9' → ❌ false | | char.IsLetterOrDigit('a') | 判斷單一字元是否為字母或數字 | 'A' → ✅ true , '5' → ✅ true , '@' → ❌ false | | "1234".All(char.IsDigit) | 判斷整個字串是否為純數字 | "1234" → ✅ true , "A12" → ❌ false | | "1234".All(char.IsLetter) | 判斷整個字串是否為純字母 | "Hello" → ✅ true , "H1" → ❌ false | | "1234".All(char.IsLetterOrDigit) | 判斷整個字串是否為字母或數字 | "A1B2" → ✅ true , "A1!" → ❌ false | | "1234".Any(char.IsLetterOrDigit)|判斷「至少有一個」包含 字母或數字 |"A1B2" → ✅ true , "A1!" → ❌ false| ```csharp= Console.WriteLine("abc123".Any(c => !char.IsLetterOrDigit(c))); // ❌ False(沒有特殊符號) Console.WriteLine("hello@world".Any(c => !char.IsLetterOrDigit(c))); // ✅ True(有 `@`) ``` ## IsNullOrWhiteSpace判斷是否為空白 結果為trun or false ```csharp= string.IsNullOrWhiteSpace(textBox2.Text) ``` ## Regex 綜合判斷(特殊符號) 正則表達式 Regex,可以用來匹配、搜尋、取代或分割字串 📌 Regex.Match() 與 Regex.Matches() 的區別 Regex.Match() 只返回 第一個 符合條件的字串。 Regex.Matches() 回傳所有符合條件的字串集合。 | 方法 | 作用 | |----------------|----------------------------------------------| | Regex.Match | 回傳第一個符合條件的 Match 物件(包含匹配的字串、索引等資訊)。 | | Regex.IsMatch | 回傳 true 或 false,用來判斷是否有符合的字串。 | ```csharp= string idNumber = "身分證字號: A123456789"; Match match = Regex.Match(idNumber, @"[A-Z]\d{9}"); string input = "12345"; bool isNumber = Regex.Match(text, @"\\d{4}-\\d{6}"); ``` 1. (\d{4}) * \d 表示「數字 (0-9)」 * {4} 表示「剛好 4 個數字」 * 例子:0912 2. (-) * 這是普通的 - 符號,表示數字與數字之間必須有一個 減號 * 例子:0912- 3. (\d{6}) * \d 表示「數字 (0-9)」 * {6} 表示「剛好 6 個數字」 4. ✅ 1234-987654 💡常用符號: | 符號 | 說明 | | --------- | ---------------------------------------- | | \d | 任意數字 (0-9) | | \w | 任意字母、數字或底線 ( [a-zA-Z0-9_] ) | | \s | 任意空白字符(空格、Tab、換行) | | . | 任意單一字元 | | + | 一個或多個 | | * | 0 個或多個 | | ? | 0 個或 1 個 | | {n,m} | 至少 n 個,最多 m 個 | | ^ | 字串開頭 | | $ | 字串結尾 | | [abc] | a, b 或 c 任一字元 | | [^abc] | 不 是 a, b, c 的任一字元 | |[#$%&!?=-_+@]|特殊符號| |(?=.*[A-Za-z]) |至少 要有 一個字母(大小寫皆可)| |(?=.*\d) |至少 要有 一個數字| ### 💡💡特殊符號判斷 我們選擇使用剃除數字和英文字母後就為特殊符號 ```csharp= string input = "Hello@World!"; // 測試字串 string pattern = @"[^\w\s]"; // 找出非字母、數字和空白的符號 if (Regex.IsMatch(input, pattern)) { Console.WriteLine("字串包含特殊符號!"); } else { Console.WriteLine("字串不含特殊符號。"); } ``` 📌 解釋@"[^\w\s]": 整體意思: 任何不是字母、數字或空格的字元,都被視為特殊符號。 * \w:代表英文字母 (a-zA-Z)、數字 (0-9) 和底線 (_)。 * \s:代表空格 (space、tab、換行 等)。 * ^:在 [] 內代表 「不包含」 的意思。 ## 函式 函數可以做為太多重複的程式碼時,可以將它塞入一個自訂的字元當中 ```csharp= static void Main(string[] args) { name("Anna"); } public static void name(string who) { Console.WriteLine(who + " hii"); } ``` ### 連結物件 static 方法無法直接存取 **非靜態** 的物件,例如 ListBox1 ListBox1 屬於 某個 Form 實例,而 static 方法沒有 this 來存取表單上的控制項 1. 改為非 static ```csharp= private void up_card() // 移除 static { ListBox1.Items.Add("新資料"); } ``` 2. 透過 this 來存取控制項 ```csharp= private static void up_card(Form1 form) { form.ListBox1.Items.Add("新資料"); } ``` 🔹 使用時: ```csharp= up_card(this); // 在 Form1 內部呼叫 ``` 3. 使用 Invoke (適用於多執行緒) 如果 up_card() 可能在不同執行緒中執行(例如 Thread 或 Task.Run()),需要用 Invoke 來更新 ```csharp= private void up_card() { if (ListBox1.InvokeRequired) { ListBox1.Invoke(new Action(up_card)); } else { ListBox1.Items.Add("新資料"); } } ``` ## 權限 存取修飾詞,它們的作用是控制類別、方法、變數等的可見性與存取權限。 ### private(私有) 只能在 "同一個類別內" 存取,其他類別無法存取。 👉 適合用來保護內部資料,防止外部修改。 ```csharp= class Example { private int secretNumber = 42; // 只有 Example 類別內部可以存取 private void ShowSecret() { Console.WriteLine(secretNumber); } } ``` ```csharp= Example ex = new Example(); Console.WriteLine(ex.secretNumber); // ❌ 錯誤,因為 `secretNumber` 是 private ``` ### public(公開) 可以被專案內的所有類別存取,甚至外部專案也可以(如果加了 using)。 👉 適合提供外部呼叫的功能,例如 Main 方法、API、工具函式。 ```csharp= class Example { public int age = 30; // 任何類別都可以讀取與修改 public void SayHello() { Console.WriteLine("Hello, World!"); } } ``` ```csharp= Example ex = new Example(); Console.WriteLine(ex.age); // ✅ 正確 ex.SayHello(); // ✅ 正確 ``` ### static(靜態) 靜態成員屬於類別本身,而不是某個實例(instance)。 👉 不需要 new 就能直接使用 類別名稱.方法名稱() 來呼叫。 ```csharp= class MathHelper { public static int Add(int a, int b) { return a + b; } } ``` ```csharp= int sum = MathHelper.Add(5, 10); // ✅ 不需要 new 物件,直接呼叫 Console.WriteLine(sum); // 15 --------------------------------------------------- MathHelper helper = new MathHelper(); int sum = helper.Add(5, 10); // ❌ 錯誤,靜態方法不能用實例呼叫 ``` ### protected(受保護) 可以被"自己"和"子類別"存取,但不能被其他類別存取。 ```csharp= class Parent { protected string familySecret = "家族秘密"; } class Child : Parent { public void ShowSecret() { Console.WriteLine(familySecret); // ✅ 正確,子類別可以存取 protected 變數 } } ``` ```csharp= Parent p = new Parent(); Console.WriteLine(p.familySecret); // ❌ 錯誤,因為 `familySecret` 是 protected ``` 修飾詞 | 可存取範圍 | 是否需要 | 典型用途 ------------|-----------------------------|-----------|--------------------------- private | 只能在同一類別內 | 需要 | 內部變數、內部方法 public | 任何地方都可以存取 | 需要 | API、工具函式、全域變數 static | 整個專案都可存取(如果是 public) | ❌ 不需要 | 數學函式、工具函式 protected | 只能在自己與子類別內 | 需要 | 繼承時的共用屬性 ## get 和 set get為讀取數值、set為存取數值 ```csharp= using System; namespace PropertyExample { internal class Person { private string name; // 私有欄位 // 定義屬性 public string Name { get { return name; } // 讀取欄位 set { if(value == "anna") // 設定欄位 name=value; else name=""; } } } internal class Program { static void Main(string[] args) { Person person = new Person(); person.Name = "Alice"; // 使用 set 存取子 Console.WriteLine(person.Name); // 使用 get 存取子 } } } ``` >感謝提供ChatGPT ## 實用小技巧 讓你更方便的使用C#~ ### 註解篇 * 選取區塊全部註解:Ctrl+K+C * 選取區塊全部取消註解:Ctrl+K+U * 註解一定範圍:/* ....... */ ```csharp= /* int old1; Console.WriteLine("年齡"); */ ``` ### 整理篇 會不會在寫程式的時候沒有空格相同都會很不爽!! * 現在只要按下Ctrl+K+E !!!