| 方法 | 輸入 null | 格式錯誤 | 回傳型別 | 適用場景 |
|---|---|---|---|---|
Int32.Parse(s) | 拋 ArgumentNullException | 拋 FormatException | int | 確定輸入合法、不想處理 bool 回傳 |
Int32.TryParse(s, out int) | 回傳 false, out=0 | 回傳 false, out=0 | bool | 首選:無例外、效能最佳、流程清晰 |
Convert.ToInt32(s) | 回傳 0 | 拋 FormatException | int | 需 null 轉 0 語意、或轉換非字串物件 |
// 標準 TryParse 模式
if (Int32.TryParse(input, out int value))
{
// 成功:使用 value
Process(value);
}
else
{
// 失敗:記錄/提示/預設值
LogWarning($"無效整數輸入:{input}");
value = GetDefaultValue();
}
// 簡潔單行 (C# 7.0+)
if (Int32.TryParse(input, out var value)) Process(value);
// 僅 Convert.ToInt32 支援指定基數 (2, 8, 10, 16)
string hex = "FF"; // 或 "0xFF" (前綴可選)
int val1 = Convert.ToInt32(hex, 16); // 255
string bin = "1010";
int val2 = Convert.ToInt32(bin, 2); // 10
// Parse/TryParse 需用 NumberStyles.HexNumber (僅十六進位,且不可有 0x 前綴)
int val3 = Int32.Parse("FF", System.Globalization.NumberStyles.HexNumber); // 255
// Int32.Parse("0xFF", NumberStyles.HexNumber) -> 拋例外!
string sci = "1.23E4"; // 12300
// 需指定允許小數點與指數符號
int val = Int32.Parse(sci,
System.Globalization.NumberStyles.AllowDecimalPoint |
System.Globalization.NumberStyles.AllowExponent);
// 或使用 Float 組合樣式 (含空白、正負號、小數點、指數)
int val2 = Int32.Parse(" 1.23E4 ", System.Globalization.NumberStyles.Float);
⚠️ 科學記號解析結果若超出 int 範圍會拋 OverflowException,建議解析為 double/decimal。
// 方法一:先 Trim (最直觀)
int val = Int32.Parse(input.Trim());
// 方法二:NumberStyles 允許前後空白
int val2 = Int32.Parse(input,
System.Globalization.NumberStyles.AllowLeadingWhite |
System.Globalization.NumberStyles.AllowTrailingWhite);
// 方法三:NumberStyles.Float 包含空白處理
int val3 = Int32.Parse(" 123 ", System.Globalization.NumberStyles.Float);
// 依系統區域設定解析貨幣符號、千分位、小數點
string currency = "$1,234.56";
int val = Int32.Parse(currency, System.Globalization.NumberStyles.Currency);
// 注意:Currency 樣式不支援十六進位
var nfi = new System.Globalization.NumberFormatInfo
{
CurrencySymbol = "NT$",
CurrencyDecimalSeparator = ".",
CurrencyGroupSeparator = ",",
CurrencyDecimalDigits = 2,
CurrencyPositivePattern = 0, // $n
CurrencyNegativePattern = 0 // ($n)
};
string custom = "NT$1,234.56";
decimal val = decimal.Parse(custom, System.Globalization.NumberStyles.Currency, nfi);
| 屬性 | 對應區域設定 | 範例 |
|---|---|---|
| CurrencySymbol | 貨幣符號 | "$", "NT$", "€" |
| CurrencyDecimalSeparator | 小數點符號 | ".", "," |
| CurrencyGroupSeparator | 千分位符號 | ",", ".", " " |
| CurrencyDecimalDigits | 小數位數 | 2 |
| NumberDecimalSeparator | 數字小數點 | ".", "," |
| NumberGroupSeparator | 數字千分位 | ",", ".", " " |
| NegativeSign | 負號 | "-", "−" |
| PositiveSign | 正號 | "+", "" |
.NET 所有基本型別 (`sbyte, byte, short, ushort, int, uint, long, ulong, float, double, decimal, bool, char, DateTime`) 均提供:
Type.Parse(string)Type.TryParse(string, out Type) (.NET 2.0+)Convert.ToType(object)選擇原則同 Int32:優先 TryParse,確定合法用 Parse,需 null 轉零用 Convert。