整理自 C# 程式設計課程課堂筆記,涵蓋語法核心、類別設計、集合介面、運算子重載等高頻知識點,適合快速複習與查漏補缺。
// out:呼叫端無需初始化,被呼叫端必須指派
void GetValues(out int a, out int b) { a = 1; b = 2; }
// ref:呼叫端必須初始化,雙向傳遞
void Swap(ref int x, ref int y) { int t = x; x = y; y = t; }
// params:可變參數陣列,方法內視為陣列
void Sum(params int[] numbers) { /* ... */ }
Sum(1, 2, 3); Sum(new int[] { 1, 2, 3 });
// using 區塊:離開範圍自動呼叫 Dispose(),適用 IDisposable 物件
using (var font = new Font("Arial", 10f))
{
// 使用 font
} // font.Dispose() 自動執行
const int MaxSize = 100; // 編譯期常數,隱含 static
enum Color { Red = 1, Green = 2 } // 底層預設 int,可指定 byte 等
int c = (int)Color.Red; // 顯式轉型
// 位元組陣列轉字串(指定編碼)
string s = Encoding.UTF8.GetString(buffer, 0, bytesRead);
// 字串轉數值(安全轉換)
int i = int.Parse(textBox.Text); // 格式錯誤拋出 FormatException
bool ok = int.TryParse(textBox.Text, out i); // 推薦:不拋出異常
修飾詞 可視範圍
public任意處
private同一類別內
protected同一類別 + 衍生類別
internal同一組件
protected internal同一組件 或 衍生類別
private protected同一組件 且 衍生類別 (C# 7.2+)
2. 靜態成員
static 欄位/屬性/方法屬於類別,非實例。
- 靜態建構子
static ClassName() { }:類別首次被存取前自動執行一次,用於初始化靜態欄位。
3. 繼承與多型
// 基底類別
public class Animal
{
public virtual void Speak() => Console.WriteLine("..."); // 可被覆寫
}
// 衍生類別
public class Dog : Animal
{
public override void Speak() => Console.WriteLine("Wang!"); // 覆寫
public new void Run() => Console.WriteLine("Running..."); // 隱藏基底同名成員
}
4. 索引器
public class Team
{
private List _members = new();
public Member this[int index] => _members[index]; // 唯讀索引器
public Member this[string name] => _members.Find(m => m.Name == name); // 字串索引器
}
5. 屬性完整語法
private int _age;
public int Age
{
get => _age;
set
{
if (value < 0) throw new ArgumentException("Age >= 0");
_age = value;
}
}
6. 運算子重載與型別轉換
public struct Roman
{
public int Value;
// 隱式轉換:int → Roman (無資料遺失)
public static implicit operator Roman(int v) => new Roman { Value = v };
// 顯式轉換:double → Roman (可能遺失精度)
public static explicit operator Roman(double d) => new Roman { Value = (int)d };
// 運算子重載
public static Roman operator +(Roman a, Roman b) => new Roman { Value = a.Value + b.Value };
public static Roman operator -(Roman a, Roman b) => new Roman { Value = a.Value - b.Value };
}
三、集合介面體系
介面 核心成員 用途
IEnumerableGetEnumerator()支援 foreach 迭代
IEnumeratorMoveNext(), Current, Reset()迭代器實作細節
ICollectionCount, CopyTo(), IsSynchronized集合基本特徵
IList索引存取、插入刪除 有序、可索引集合
IDictionaryKey/Value 對應 關聯式集合
IComparableCompareTo(object)型別內建排序邏輯
ArrayList 常用方法 (舊版非泛型,現建議用 List<T>)
var list = new ArrayList();
list.Add(obj); list.Count; list.Clear();
list.Reverse(); list.Sort(); // 需元素實作 IComparable
四、介面進階
public interface IAnimal { void Speak(); }
public interface IMovable { void Move(); }
// 多重介面實作
public class Cat : IAnimal, IMovable
{
public void Speak() => Console.WriteLine("Meow");
public void Move() => Console.WriteLine("Walking");
}
// 介面型別測試與轉換
object obj = new Cat();
if (obj is IAnimal a) a.Speak(); // 模式比對 (C# 7+)
IAnimal b = obj as IAnimal; // 安全轉換,失敗回傳 null
if (b != null) b.Speak();
五、常用命名空間
System:基礎型別、Console, Math, Exception
System.Collections.Generic:List<T>, Dictionary<TKey,TValue>, HashSet<T>
System.Linq:LINQ 擴充方法
System.Text:StringBuilder, Encoding
System.IO:檔案、串流操作
熟練掌握上述語法模式,是高效撰寫 C# 程式的基石。建議配合 IDE (Visual Studio / Rider) 的程式碼片段與重構功能,將常用樣板內化為指尖記憶。