類別定義了物件擁有的資料(欄位/屬性)與行為(方法)。實例化即依藍圖建立具體物件。
public class Doctor {
// 欄位
private string _name;
private byte _age;
// 建構函式多載
public Doctor() { }
public Doctor(string name, byte age) => (_name, _age) = (name, age);
// 屬性(封裝欄位)
public string Name { get => _name; set => _name = value; }
public byte Age { get => _age; set => _age = value; }
// 實例方法
public string DoWork() => "我會給人治病喔~";
// 靜態方法
public static string DoAnother() => "執行的另一個靜態方法";
}
// 使用
var dc1 = new Doctor { Name = "李四", Age = 25 };
var dc2 = new Doctor("張三", 35);
Console.WriteLine(dc1.DoWork());
Console.WriteLine(Doctor.DoAnother()); // 靜態方法透過類別名呼叫
| 關鍵字 | 傳遞方式 | 適用型別 | 可修改原值? |
|---|---|---|---|
| (無) | 值傳遞 | 值型別:複製值 參考型別:複製參考 | 值型別:否 參考型別:可修改物件內容,不可換參考 |
ref | 參考傳遞 | 值/參考型別 | 是(含換新物件) |
out | 輸出參數 | 值/參考型別 | 是(建構函式前必指派) |
in (C# 7.2+) | 唯讀參考 | 參考型別/大型結構 | 否(編譯器強制) |
static void Modify(int[] arr, int x) {
arr[0] = 100; // 修改陣列元素(參考型別內容)
x = 10; // 修改區域副本
}
static void Main() {
int[] a = { 0, 1, 2 };
int y = 30;
Modify(a, y);
Console.WriteLine($"{a[0]}, {y}"); // 輸出: 100, 30
}
static bool TryParseInt(string s, out int result) {
return int.TryParse(s, out result); // 直接透傳
}
static void Main() {
if (TryParseInt("123", out int val))
Console.WriteLine(val); // 123
}
static int Add(int a) => a + 100;
static string Add(string s) => s;
static int Add(int a, int b) => a + b;
// 呼叫時編譯器依引數型別自動綁定
類別封裝資料與行為,方法實作演算法邏輯。精通參數傳遞語意、多載規則與現代 C# 語法糖,是寫出高品質程式碼的基石。