C# 型別系統劃分為兩大陣營:
int i = 10;
int j = i; // j 獲得獨立副本
j = 20; // i 仍為 10
記憶體中存在兩個獨立的 10,互不干擾。
Vector x = new Vector(); // 假設 Vector 為 class
x.Value = 20;
Vector y = x; // y 指向同一物件
y.Value = 50;
Console.WriteLine(x.Value); // 輸出 50!
x 與 y 指向同一堆積物件,修改任一者均影響另一者。參考型別可指派 null 表示不指向任何物件。
C# 預定義型別並非語言內建,而是對應 .NET 執行期型別:
int → System.Int32double → System.Doublebool → System.Boolean這意味著所有基礎型別皆為結構/類別,擁有方法(如 int.MaxValue、ToString()),實現了「一切皆物件」的統一性。
| 型別 | 位元 | 範圍 | CLR 對應 |
|---|---|---|---|
| sbyte | 8 | -128 ~ 127 | System.SByte |
| byte | 8 | 0 ~ 255 | System.Byte |
| short | 16 | -32,768 ~ 32,767 | System.Int16 |
| ushort | 16 | 0 ~ 65,535 | System.UInt16 |
| int | 32 | -2,147,483,648 ~ 2,147,483,647 | System.Int32 |
| uint | 32 | 0 ~ 4,294,967,295 | System.UInt32 |
| long | 64 | -2^63 ~ 2^63-1 | System.Int64 |
| ulong | 64 | 0 ~ 2^64-1 | System.UInt64 |
float (32-bit, ~7 位有效數字) —— 字面值加 f 後綴:3.14fdouble (64-bit, ~15 位) —— 預設浮點字面值型別decimal (128-bit, 28-29 位) —— 財務計算首選,字面值加 m:19.99mbool:true/falsechar:單一 Unicode 字元 (16-bit),單引號括起:'中';雙引號為字串 "中"所有型別隱含繼承 System.Object,提供 Equals()、GetHashCode()、GetType() 等虛擬方法,可覆寫實現自訂相等邏輯。
string 雖為參考型別,但語意上表現為不可變值型別:
string s1 = "GoSoA";
string s2 = s1; // 共用同一字串物件
s1 = "www.GoSoA"; // s1 指向新物件,s2 仍指向原物件
// 輸出:s1=www.GoSoA, s2=GoSoA
修改字串實為建立新物件,原物件不變,這是為了執行緒安全與字串駐留優化。