當不存在隱式轉換時,從一種數值類型轉換到另一種數值類型,必須使用顯式轉換(Cast)。這意味著你必須在代碼中明確指示編譯器:「我知道這可能損失精度或拋出例外,但我確定要這麼做。」
| 來源類型 | 目標類型 |
|---|---|
| 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 |
編譯器會進行溢出檢測。若未溢出則轉換成功,否則拋出 OverflowException。此行為受 checked/unchecked 語境影響。
值會捨入至最接近的整數。若超出目標類型範圍,拋出 OverflowException。
捨入至最接近的 float。太小變 ±0,太大變 ±無窮大,NaN 保持 NaN。
轉為十進位並捨入至小數點後 28 位。太小變 0,太大或為無窮大/NaN 時拋出 InvalidCastException。
捨入至最接近值,可能損失精度,但不會引發例外。
using System;
class Test {
static void Main() {
long longValue = Int64.MaxValue; // 9223372036854775807
int intValue = (int)longValue; // 顯式轉換
Console.WriteLine("(int){0}={1}", longValue, intValue);
}
}
輸出結果: (int)9223372036854775807=-1
原因:long 最大值遠超 int 範圍,發生溢出,導致資訊遺失,產生負數結果。這正是顯式轉換必須謹慎使用的理由。