顯式數值轉換(強制轉型)用於不存在隱含轉換的數值型別之間。開發者必須以 (TargetType)value 語法明確表達意圖,並承擔資訊遺失或執行期例外的風險。
| 來源 | 可顯式轉換的目標型別 |
|---|---|
sbyte | byte, ushort, uint, ulong, char |
byte | sbyte, char |
short | sbyte, byte, ushort, uint, ulong, char |
ushort | sbyte, byte, short, char |
int | sbyte, byte, short, ushort, uint, ulong, char |
uint | sbyte, byte, short, ushort, int, char |
long | sbyte, byte, short, ushort, int, uint, ulong, char |
ulong | sbyte, byte, short, ushort, int, uint, long, char |
char | sbyte, byte, short |
float | sbyte, byte, short, ushort, int, uint, long, ulong, char, decimal |
double | sbyte, byte, short, ushort, int, uint, long, ulong, char, float, decimal |
decimal | sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double |
checked 內容下溢位拋 OverflowException;unchecked 截斷高位。MidpointRounding.ToEven);超出範圍拋 OverflowException。double → float:IEEE 754 捨入;太小變 ±0,太大變 ±∞,NaN 保持 NaN。decimal:轉十進位並捨入至 28 位;太小成 0,太大/∞/NaN 拋 InvalidCastException。decimal → 浮點/雙精度:捨入至最接近值;可能損失精度但不拋例外。
long max = long.MaxValue; // 9223372036854775807
int i = (int)max; // 在 unchecked 預設下 → -1
// checked { int j = (int)max; } // 拋 OverflowException
輸出 (int)9223372036854775807 = -1,證明高位被截斷(補數表示)。