每個變數宣告必須指定型別,編譯器才能配置正確記憶體。C# 型別系統分為兩大派系:
儲存於 Stack(區域變數)或 Inline 於包含物件中。指派 = 複製實體。
| 關鍵字 | .NET 型別 | 分類 |
|---|---|---|
sbyte | System.SByte | 整數 |
byte | System.Byte | |
short | System.Int16 | |
ushort | System.UInt16 | |
int | System.Int32 | |
uint | System.UInt32 | |
long | System.Int64 | |
ulong | System.UInt64 | |
float | System.Single | 浮點 |
double | System.Double | |
decimal | System.Decimal | 十進位 |
bool | System.Boolean | 布林 |
char | System.Char | 字元 |
詳細內容請參閱各專題文章:整數、布林、浮點/Decimal、字元。
structPoint、DateTime、Guid)Nullable<T>)enumvar point = (X: 10, Y: 20); // ValueTuple<int, int> - 值型別
var (x, y) = point; // 解構
Console.WriteLine($"{point.X}, {point.Y}");
out 參數或自訂類別ValueTuple 為結構(值型別),Tuple 為類別(參考型別)Nullable<T> (T?)int? count = null; // Nullable<int>
if (count.HasValue) Console.WriteLine(count.Value);
實際資料在 Heap,變數持有參考。指派 = 複製參考(指向同一物件)。
class:類別string:字串(不可變,特殊參考型別)array:陣列delegate:委派interface:介面object:所有型別基底dynamic:動態型別Stack (執行緒專屬,LIFO,自動管理) ├── 區域值型別變數 (int, struct, enum, Tuple) ├── 區域參考型別變數 (指向 Heap 物件的指標) └── 方法呼叫框架 (參數、返回位址) Heap (共用、GC 管理) ├── 類別實例 ├── 陣列 ├── 字串 ├── 委派實例 └── 箱裝後的值型別 (boxing)
int i = 123;
object o = i; // 裝箱:值型別 → 參考型別 (Heap 配置、複製值)
int j = (int)o; // 拆箱:參考型別 → 值型別 (驗證型別、複製值)
// 效能影響:頻繁裝箱產生 GC 壓力
List<object> list = new List<object>();
for (int k = 0; k < 10000; k++) list.Add(k); // 10000 次裝箱!
// 解法:用 List<int> 或泛型避免裝箱
struct 預設 public,類別預設 internalnull,值型別預設零值. 存取成員,無 ->/::C# 型別系統以值/參考二分為核心,簡單型別、結構、列舉、Tuple 構建值型別家族,類別、字串、陣列、委派構建參考型別家族。理解記憶體模型、裝箱拆箱、指派語意差異,是寫出高效正確 C# 代碼的基石。