| 方法 | 語法 | 適用輸入 | 小數處理 | 錯誤處理 | 效能 |
|---|---|---|---|---|---|
| 強制轉型 | `(int)doubleVal` | 數值型別 | **截斷** (Truncate) | 無 (溢位不可檢測) | 最快 |
| Convert.ToInt32 | `Convert.ToInt32(obj)` | 任意物件 (含 null、字串、數值) | **四捨五入** (Banker's Rounding) | null→0、格式錯誤→FormatException、溢位→OverflowException | 中 |
| int.Parse | `int.Parse(str)` | **純整數字串** | **拋出例外** (非整數字串) | FormatException / OverflowException | 中 |
| int.TryParse | `int.TryParse(str, out int)` | 字串 | **拋出例外** (非整數字串) | 回傳 bool,失敗 out=0,**無例外** | 最佳 (避免例外開銷) |
// 1. 小數數值
double d = 2.8;
int a = (int)d; // 2 (截斷)
int b = Convert.ToInt32(d); // 3 (四捨五入:Banker's Rounding 到最近偶數)
int c = Convert.ToInt32(2.5); // 2 (Banker's Rounding: .5 到偶數)
int d = Convert.ToInt32(3.5); // 4
// 2. 字串 "2.8"
int e = int.Parse("2.8"); // FormatException: 輸入字串格式不正確
int f = Convert.ToInt32("2.8"); // FormatException (Convert 內部呼叫 Parse)
int g = -1; int.TryParse("2.8", out g); // false, g=0
// 3. 字串 "abc"
int h = int.Parse("abc"); // FormatException
int i = Convert.ToInt32("abc"); // FormatException
int j = -1; int.TryParse("abc", out j); // false, j=0
// 4. null 物件
object o = null;
int k = Convert.ToInt32(o); // 0 (不拋出)
int l = (int)o; // NullReferenceException
int m = int.Parse((string)o); // ArgumentNullException
`Convert.ToInt32` / `Math.Round` 預設使用 **MidpointRounding.ToEven**:`.5` 進位到最近的**偶數**。
ReadOnlySpan span = "12345".AsSpan();
if (int.TryParse(span, out int val)) { ... } // 避免子字串配置
**`int.TryParse` 是字串轉整數的黃金標準**:無例外、效能最佳、語意清晰。`Convert.ToInt32` 適合物件來源多樣且接受四捨五入語意。強制轉型僅限數值型別且接受截斷。切記:**字串 "2.8" 無法直接 Parse 為 int**,需先 `double.Parse` 再轉型,或自行處理小數點。