**基元型別** 是 C# 編譯器內建、直接對應 CLI 規範基本型別的關鍵字。它們不是類別,而是編譯器與 CLR 之間的特殊契約。理解基元型別,能解開 int vs Int32、string vs String 等經典困惑,並看懂 IL 本質。
| C# 關鍵字 | FCL 完整型別 | CLS 合規 | 大小 | 範圍 / 精度 | 預設值 |
|---|---|---|---|---|---|
sbyte | System.SByte | ❌ | 1 byte | -128 ~ 127 | 0 |
byte | System.Byte | ✅ | 1 byte | 0 ~ 255 | 0 |
short | System.Int16 | ✅ | 2 bytes | -32,768 ~ 32,767 | 0 |
ushort | System.UInt16 | ❌ | 2 bytes | 0 ~ 65,535 | 0 |
int | System.Int32 | ✅ | 4 bytes | -2,147,483,648 ~ 2,147,483,647 | 0 |
uint | System.UInt32 | ❌ | 4 bytes | 0 ~ 4,294,967,295 | 0 |
long | System.Int64 | ✅ | 8 bytes | -9.22e18 ~ 9.22e18 | 0L |
ulong | System.UInt64 | ❌ | 8 bytes | 0 ~ 1.84e19 | 0UL |
char | System.Char | ✅ | 2 bytes | U+0000 ~ U+FFFF | '\0' |
float | System.Single | ✅ | 4 bytes | ±1.5e−45 ~ ±3.4e38 (~7 位有效數字) | 0f |
double | System.Double | ✅ | 8 bytes | ±5e−324 ~ ±1.7e308 (~15-16 位) | 0d |
decimal | System.Decimal | ✅ | 16 bytes | ±1e−28 ~ ±7.9e28 (28-29 位精確) | 0m |
bool | System.Boolean | ✅ | 1 byte | true/false | false |
object | System.Object | ✅ | 參考 | 所有型別基底 | null |
string | System.String | ✅ | 參考 | Unicode 字串 | null |
// C# 原始碼
int a = 0;
Int32 b = 0;
int c = new int();
System.Int32 d = new System.Int32();
// 編譯後 IL (Release 模式)
.locals init ([0] int32 a, [1] int32 b, [2] int32 c, [3] int32 d)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldc.i4.0
IL_0003: stloc.1
IL_0004: ldc.i4.0
IL_0005: stloc.2
IL_0006: ldc.i4.0
IL_0007: stloc.3
IL_0008: ret
**結論**:四種寫法編譯為**完全相同的 IL**。int是System.Int32的編譯器別名,new int()只是initobj指令的語法糖,皆產生ldc.i4.0初始化。
string:C# 關鍵字,**必須** using System; 才能用 String。String:FCL 型別名稱,跨語言通用(VB.NET 用 String)。string,靜態方法呼叫用 String (如 String.Format、String.Compare)。Int32 i = 10;
Int64 l = i; // 隱式轉換
// IL
IL_0000: ldc.i4.s 10
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: conv.i8 // 關鍵指令:符號擴展 32→64 位
IL_0005: stloc.1
conv.* 指令,**無需程式碼檢查**。(Type) 強制,CLR 發 conv.ovf.* (檢查溢位) 或 conv.* (截斷)。Int32、Int64 皆為 value type,**無繼承關係**,但 CLR 內建支援數值型別間的隱式/顯式轉換,這是 CLI 規範特例。using int32 = System.Int32; // 合法
using MyInt = System.Int32; // 合法
// using int = System.Int32; // ❌ 錯誤:int 是關鍵字,不可作別名目標
int, string, bool...):可讀性最高、團隊慣例一致。Int32, String) 增強跨語言清晰度。sbyte, ushort, uint, ulong) 出現在 public/protected 介面,改用 byte, short, int, long。float/double,**強制 decimal**。[MarshalAs(UnmanagedType.I4)] 等屬性,勿依賴關鍵字預設對應。基元型別是 C# 與 CLR 之間的**原生契約**。關鍵字只是 FCL 型別的編譯時別名,IL 層面完全一致。掌握對照表、CLS 合規性、轉換指令與慣例,即能寫出型別安全、跨語言友善、效能可預期的程式碼。