萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C# 字串轉整數三大方法差異總結:強制轉型、Convert.ToInt32、int.Parse/TryParse

三大方法速查

方法語法適用輸入小數處理錯誤處理效能
強制轉型`(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

Banker's Rounding (銀行家算法) 說明

`Convert.ToInt32` / `Math.Round` 預設使用 **MidpointRounding.ToEven**:`.5` 進位到最近的**偶數**。

  • `2.5 → 2`, `3.5 → 4`
  • 若需傳統「四捨五入」 (AwayFromZero):`(int)Math.Round(val, MidpointRounding.AwayFromZero)`

最佳實踐選擇指南

  1. 已知為數值型別、需截斷 → `(int)val` (最快、語意明確)。
  2. 物件來源不確定、可能為 null、需四捨五入 → `Convert.ToInt32(obj)`。
  3. 字串輸入、預期為合法整數、例外即為 Bug → `int.Parse(str)`。
  4. 字串輸入、可能非法、高頻呼叫、不想要 try-catch → `int.TryParse(str, out var result)` **首選**。
  5. 需精確控制四捨五入模式 → `Math.Round` + `MidpointRounding` 再轉型。

進階:Span-based TryParse (.NET Core 2.1+ / .NET 5+)


ReadOnlySpan span = "12345".AsSpan();
if (int.TryParse(span, out int val)) { ... } // 避免子字串配置

總結

**`int.TryParse` 是字串轉整數的黃金標準**:無例外、效能最佳、語意清晰。`Convert.ToInt32` 適合物件來源多樣且接受四捨五入語意。強制轉型僅限數值型別且接受截斷。切記:**字串 "2.8" 無法直接 Parse 為 int**,需先 `double.Parse` 再轉型,或自行處理小數點。

copyright © 萬盛學電腦網 all rights reserved