三者皆可將字串轉為 int,但錯誤處理行為截然不同:
| 方法 | 輸入 null | 輸入非數字 | 回傳值 | 適用場景 |
|---|---|---|---|---|
Convert.ToInt32(str) |
回傳 0 | 拋 FormatException | int | 允許 null 轉 0 的業務邏輯 |
Int32.Parse(str) |
拋 ArgumentNullException | 拋 FormatException | int | .NET 1.1 時代遺留,確定輸入合法時使用 |
Int32.TryParse(str, out int) |
回傳 false,out=0 | 回傳 false,out=0 | bool | 現代首選,無例外、效能最佳、程式碼清晰 |
實測百萬次迴圈下,三者差異極微(奈秒級)。TryParse 略勝一籌,因內部直接呼叫 Number.TryParseInt32,少一層委派呼叫。
// 推薦寫法
if (Int32.TryParse(userInput, out int value))
{
// 成功
}
else
{
// 失敗處理
}
string data = "1234,234523,4324,324";
// 用法一:分隔字元陣列 (可多字元分隔)
string[] parts1 = data.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
// 用法二:單一分隔字元 (最常用)
string[] parts2 = data.Split(',');
// 用法三:Regex.Split 依正則分割 (支援多字元、模式分隔)
string[] parts3 = System.Text.RegularExpressions.Regex.Split(data, @",\s*");
var cleanParts = data.Split(',')
.Select(s => s.Trim())
.Where(s => !string.IsNullOrEmpty(s))
.ToArray();
| 特性 | 一般字串 "..." | 逐字字串 @"..." |
|---|---|---|
| 逸出字元 | 需雙重逸出 \\ \n | 忽略逸出,原樣輸出 |
| 跨行 | 需用 \n 或 + 串接 | 可直接換行撰寫 |
| 路徑表示 | "C:\\Windows\\System" | @"C:\Windows\System" |
| 雙引號內嵌 | "He said \"Hi\"" | @"He said ""Hi""" (雙寫雙引號) |
double value = 12.345678;
// 方法一:Math.Round (銀行家算法:四捨六入五成雙)
double r1 = Math.Round(value, 2); // 12.35
double r2 = Math.Round(12.345, 2, MidpointRounding.AwayFromZero); // 12.35 (傳統四捨五入)
// 方法二:ToString 格式化 (僅顯示用)
string s1 = value.ToString("F2"); // "12.35"
string s2 = value.ToString("N2"); // "12.35" (含千分位)
// 方法三:手動運算 (不推薦,易溢位)
double r3 = Math.Floor(value * 100 + 0.5) / 100;
金融計算警示:涉及金額計算請使用decimal型別搭配Math.Round(value, 2, MidpointRounding.AwayFromZero),避免二進位浮點誤差。
ToString("##-###-####") 或 Regex 替換。ToCharArray 陣列交換。rnd.Next(10) 比 % 10 更直觀。new string('A', 21)。string.Compare(a, b, StringComparison.OrdinalIgnoreCase)。