C# 的型別系統分為兩大類別:值類型 與 參考類型。理解兩者在記憶體配置、複製行為與效能上的差異,是撰寫高效、正確程式碼的基礎。
值類型變數直接包含資料,儲存在 堆疊 上,具有固定長度。每個變數擁有獨立的資料副本,操作互不干擾。
| 分類 | 關鍵字 | .NET 對應型別 | 大小 | 範例 |
|---|---|---|---|---|
| 整數 | sbyte | System.SByte | 8 位 | sbyte v = -12; |
| byte | System.Byte | 8 位 | byte v = 255; | |
| short | System.Int16 | 16 位 | short v = 32000; | |
| ushort | System.UInt16 | 16 位 | ushort v = 65000; | |
| int | System.Int32 | 32 位 | int v = 123; | |
| uint | System.UInt32 | 32 位 | uint v = 456U; | |
| long | System.Int64 | 64 位 | long v = 789L; | |
| ulong | System.UInt64 | 64 位 | ulong v = 100UL; | |
| char | System.Char | 16 位 | char c = 'A'; | |
| 浮點數 | float | System.Single | 32 位 | float f = 1.23F; |
| double | System.Double | 64 位 | double d = 4.56; | |
| 高精度 | decimal | System.Decimal | 128 位 | decimal m = 1.23M; |
| 布林 | bool | System.Boolean | 1 位 | bool b = true; |
使用 struct 定義,同樣屬於值類型,儲存在堆疊。適合輕量、不可變的資料結構。
public struct Point
{
public int X;
public int Y;
public string Label;
}
結構 vs 類別:結構為值類型(堆疊),類別為參考類型(堆積)。結構不支援繼承,但可實作介面。
使用 enum 定義具名常數集合,預設底層型別為 int。
enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat }
enum Status { Low = 1, Medium = 5, High = 10 }
參考類型變數儲存記憶體位址,實際物件配置在 受控堆積 上。多個變數可參考同一物件,修改會互相影響。
classinterfacedelegatestring(不可變參考類型)string s = "Hello";
char c = s[1]; // 'e'
bool equal = (s == "Hello"); // 內容比較
int cmp = string.Compare(s, "World"); // -1/0/1
int i = 123;
double d = 123.456;
Console.WriteLine(i.ToString("D8")); // 00000123
Console.WriteLine(d.ToString("F2")); // 123.46
Console.WriteLine(d.ToString("N")); // 123.46 (含千分位)
Console.WriteLine((0.126).ToString("P")); // 12.60%
Console.WriteLine(string.Format("i:{0,-7}, j:{1,7}", i, d));
string[] arr1 = { "C", "C++" };
int[] arr2 = new int[4] { 0, 1, 2, 3 };
int[] arr3 = { 5, 6, 7 };
int[,] matrix = { {0,1}, {2,3}, {4,5} };
int[,] m2 = new int[5, 3];
string[][] jagged = new string[3][];
jagged[0] = new string[2] { "a", "b" };
jagged[1] = new string[3] { "c", "d", "e" };
int → long),無資料遺失風險long → int),需加括號 (int)val,可能截斷資料implicit/explicit 運算子多載將值類型轉為 object(參考類型)稱為 裝箱;反之為 拆箱。
int i = 123;
object boxed = i; // 裝箱:配置堆積記憶體、複製數值
int j = (int)boxed; // 拆箱:檢查型別、複製回堆疊
效能提醒:頻繁裝箱/拆箱會增加 GC 壓力,建議使用泛型集合(List<T>)避免。
C# 2.0 引入 Nullable<T>(簡寫 T?),允許值類型表達「無值」狀態。
int? count = null;
if (count.HasValue) Console.WriteLine(count.Value);
Console.WriteLine(count ?? 0); // null 聯合運算子