在表單驗證、資料匯入、API 參數檢核等情境中,「判斷字串是否為純數字」是極高頻的需求。本文整理四種常見做法,並從可讀性、效能、適用場景三個維度分析優劣,助你選出最適合專案的方案。
public static bool IsNumeric(string str)
{
if (string.IsNullOrEmpty(str)) return false;
foreach (char c in str)
if (!char.IsNumber(c)) return false;
return true;
}
TryParse。public static bool IsNumericAscii(string s)
{
if (string.IsNullOrEmpty(s)) return false;
for (int i = 0; i < s.Length; i++)
if (s[i] < '0' || s[i] > '9') return false;
return true;
}
private static readonly Regex NumericRegex = new Regex(@"^[-]?\d+(\.\d+)?$", RegexOptions.Compiled);
public static bool IsNumericRegex(string str)
=> !string.IsNullOrEmpty(str) && NumericRegex.IsMatch(str);
RegexOptions.Compiled 與靜態快取。public static bool IsNumericTryParse(string str, out double result)
=> double.TryParse(str, NumberStyles.Any, CultureInfo.InvariantCulture, out result);
// 泛型擴充:支援 int/long/decimal/float/double
public static bool TryParseNumber<T>(string str, out T result) where T : struct, IParsable<T>
=> T.TryParse(str, null, out result);
System.Globalization。| 方法 | 平均耗時 (ms) | 相對倍數 |
|---|---|---|
| ASCII 範圍 | 12 | 1.0x (基準) |
| Char.IsNumber | 28 | 2.3x |
| double.TryParse | 45 | 3.8x |
| Regex (Compiled) | 210 | 17.5x |
註:實際差距視字串長度、CPU、.NET 版本而異;TryParse 雖非最快,但功能最完整,通常為最佳綜合選擇。
TryParse 一択。Char.IsNumber。public static class NumberValidator
{
public static bool IsValid<T>(string input, out T value) where T : struct, IParsable<T>
=> T.TryParse(input, CultureInfo.InvariantCulture, out value);
// 自訂規則範例:正整數且 < 10000
public static bool IsPositiveIntUnder(string input, int max, out int value)
=> int.TryParse(input, out value) && value > 0 && value < max;
}
沒有銀彈,只有最適合當前語境的工具。建議專案建立統一的 StringExtensions.IsNumeric() 擴充方法,內部採 TryParse 實作,特殊效能熱點再局部優化為 ASCII 比對。如此既保持程式碼一致性,又能在關鍵路徑榨乾效能。