有人以為 int 是 16 位元、Convert.ToInt32 是 32 位元。錯誤! 在 C# 中 int 就是 System.Int32 的別名,兩者皆為 32 位元有號整數。
| 特性 | (int) 強制轉型 | Convert.ToInt32 |
|---|---|---|
| 分類 | 型別轉換 | 內容轉換 / 解析 |
| 適用來源 | 相容數值型別(long, double, short 等) | 任何實作 IConvertible 的物件(string, object, double, decimal 等) |
| string 處理 | 編譯錯誤(型別不相容) | 支援 解析字串數字 |
| 溢位檢查 | 無(截斷高位,可能產生錯誤結果) | 有(超出範圍拋出 OverflowException) |
| null 處理 | 不可用於 nullable 型別直接轉換 | 傳入 null 回傳 0(不拋出例外) |
string text = "1412";
int id = (int)text; // CS0030: 無法將 'string' 轉換為 'int'
string text = "1412";
int id = Convert.ToInt32(text); // 1412
int id2 = Int32.Parse(text); // 1412
int id3 = Int32.TryParse(text, out var result); // 安全嘗試解析
double d = int.MaxValue + 0.1412;
int i1 = (int)d; // 結果:-2147483648 (截斷溢位,錯誤數值)
int i2 = Convert.ToInt32(d); // 拋出 OverflowException
double → int、long → int):若確定數值在範圍內,(int) 效能略優;若需安全檢查,用 Convert.ToInt32。Convert.ToInt32、Int32.Parse 或 Int32.TryParse(建議優先用 TryParse 避免例外開銷)。object obj = 123; int v = (int)obj; 正確;若 obj 可能為 string,需先判斷型別或用 Convert.ToInt32(obj)。(int) 是編譯期型別檢查的強制轉換,僅限相容數值型別;Convert.ToInt32 是執行期內容解析,支援字串、物件、溢位檢查、null 安全。兩者不可互換,依來源資料型別與安全需求選擇。