| 特性 | 實例字段 | 本地變量 |
|---|---|---|
| 生存期 | 從對象創建到不可訪問 | 從聲明處到代碼塊結束 |
| 隱式初始化 | 默認值 (0/null/false) | 無,使用前必須賦值否則編譯錯誤 |
| 存儲位置 | 堆 (Heap) | 值類型→棧;引用類型→引用在棧,對象在堆 |
// 編譯器從右側推斷類型
var i = 10; // int
var s = "hello"; // string
var list = new List(); // List
var anon = new { Name = "Tom", Age = 25 }; // 匿名類型
// 限制:必須初始化、不能為 null、不能作為字段/屬性/參數類型
默認傳遞機制。調用時:
void Modify(ref int x) {
x = 20; // 直接修改實參內存位置的值
}
int a = 10;
Modify(ref a); // a 變為 20
// 特點:
// - 不為形參分配新內存
// - 形參成為實參的別名
// - 實參必須是已賦值的變量
void GetValues(out int x, out int y) {
x = 10; // 必須在方法返回前賦值
y = 20;
}
int a, b;
GetValues(out a, out b); // 調用前無需初始化
// 與 ref 差異:
// - out 不要求調用前賦值
// - 方法內部必須賦值 (確定性賦值規則)
// - 適用於「嘗試獲取」模式:bool TryParse(string s, out int result)
private string _name;
public string Name {
get => _name; // 讀取
set => _name = value?.Trim(); // 寫入,value 為隱式參數
}
// 自動屬性 (C# 3.0+)
public int Age { get; set; }
// 只讀自動屬性 (C# 6.0+)
public DateTime CreatedAt { get; } = DateTime.Now;
// init 只寫入構造器 (C# 9.0+)
public string Id { get; init; }
public class Point {
public int X { get; set; }
public int Y { get; set; }
public int Z { get; set; }
public Point(int z) => Z = z;
}
// 三種形式
var p1 = new Point { X = 4, Y = 5, Z = 6 }; // 無參構造 + 屬性設置
var p2 = new Point(9) { X = 7, Y = 8 }; // 帶參構造 + 屬性設置
var p3 = new Point(9) { X = 7, Y = 8, Z = 10 }; // 構造參數會被屬性覆蓋
this.name = name;OtherService.Register(this);return this;public int this[int i] { get; set; }// 值類型 (struct, int, bool 等)
int a = 10; // 棧: [a: 10]
int b = a; // 棧: [a: 10][b: 10] 獨立副本
b = 20; // 棧: [a: 10][b: 20] a 不變
// 引用類型 (class, string, array)
var p1 = new Point { X = 1 }; // 棧: [p1: ref] → 堆: [Point{X=1}]
var p2 = p1; // 棧: [p1: ref][p2: ref] → 同一堆對象
p2.X = 99; // 堆: [Point{X=99}] p1.X 也變為 99
這 8 個知識點構成了 C# 類型系統、參數傳遞、對象模型的基石。深入理解值/引用語義差異、參數修飾符語義、自動屬性演進、this 語境限制,能避開 80% 的初中級面試陷阱與生產 Bug。建議結合 ILSpy 查看編譯後 IL 代碼,從底層視角驗證理解。