隱式數值轉換本質上是從低精度/小範圍類型向高精度/大範圍類型的安全擴展。編譯器保證不會遺失資訊(極少數情況可能損失精度但不會改變數量級)。
| 來源類型 | 目標類型 |
|---|---|
| sbyte | short, int, long, float, double, decimal |
| byte | short, ushort, int, uint, long, ulong, float, double, decimal |
| short | int, long, float, double, decimal |
| ushort | int, uint, long, ulong, float, double, decimal |
| int | long, float, double, decimal |
| uint | long, ulong, float, double, decimal |
| long | float, double, decimal |
| ulong | float, double, decimal |
| char | ushort, int, uint, long, ulong, float, double, decimal |
| float | double |
int/uint/long → float:可能損失精度(float 只有 7 位有效數字),但不會改變數量級。long → double:同樣可能損失精度,但數量級保持。其他整數類型不能自動轉換為 char,這點需特別注意。
byte x = 16;
ushort y = x; // 隱式:byte → ushort
y = 65535; // ushort 最大值
float z = y; // 隱式:ushort → float
// 輸出:x=16, y=16, y=65535, z=65535
// y = y + 1; // 編譯錯誤:y+1 為 int,無隱式轉換至 ushort
// 錯誤訊息:cannot implicitly convert type 'int' to type 'ushort'
當 ushort 最大值 65535 加 1 變為 65536(int)時,無法隱式存回 ushort,必須顯式轉換。