| 方法 | 命名空間 | 適用場景 | 效能 | 備註 |
|---|---|---|---|---|
int.TryParse |
System | 驗證並轉換整數 | ⭐⭐⭐⭐⭐ | 無例外、可直接取值、支援 NumberStyles |
double.TryParse |
System | 驗證並轉換浮點數 | ⭐⭐⭐⭐⭐ | 同上 |
char.IsDigit |
System | 單字元是否 0-9 | ⭐⭐⭐⭐⭐ | 僅 ASCII 數字;全形數字需 char.GetUnicodeCategory |
char.IsLetter |
System | 單字元是否字母 | ⭐⭐⭐⭐⭐ | 包含中文/日文/韓文等 Unicode 字母 |
char.IsLetterOrDigit |
System | 單字元字母或數字 | ⭐⭐⭐⭐⭐ | 常用於驗證用戶名合法字元 |
Regex.IsMatch |
System.Text.RegularExpressions | 複雜模式驗證 | ⭐⭐⭐ | 編譯緩存 RegexOptions.Compiled 可提升 |
str.All(char.IsDigit) |
System.Linq | 全字串純數字檢查 | ⭐⭐⭐⭐ | 空字串回傳 true,需額外判斷 |
string input = textBox.Text.Trim();
if (int.TryParse(input, out int number))
{
// 成功:number 為轉換後的整數
ProcessNumber(number);
}
else
{
// 失敗:非整數格式 (含空白、字母、溢位等)
MessageBox.Show("請輸入有效整數");
}
✅ **優點**:無例外開銷、單次操作完成驗證+轉換、處理前導/尾隨空白、支援正負號。
bool isAllDigits = !string.IsNullOrEmpty(input) && input.All(char.IsDigit);
// 僅 ASCII 0-9
bool isAsciiDigits = Regex.IsMatch(input, @"^\d+$");
// 或 Unicode 數字類別
bool isUnicodeDigits = Regex.IsMatch(input, @"^\p{Nd}+$");
bool IsAllDigits(string s)
{
if (string.IsNullOrEmpty(s)) return false;
foreach (char c in s)
if (c < '0' || c > '9') return false;
return true;
}
bool isAllLetters = !string.IsNullOrEmpty(input) && input.All(char.IsLetter);
bool isAsciiLetters = Regex.IsMatch(input, @"^[A-Za-z]+$");
// 至少一字母 + 一數字,長度 6-20,僅字母數字
bool isValidAccount = Regex.IsMatch(input, @"^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,20}$");
public class CharTypeStats
{
public int Digits { get; set; }
public int Letters { get; set; }
public int UpperCase { get; set; }
public int LowerCase { get; set; }
public int Special { get; set; }
}
public static CharTypeStats Analyze(string s)
{
var stats = new CharTypeStats();
foreach (char c in s)
{
if (char.IsDigit(c)) stats.Digits++;
else if (char.IsLetter(c))
{
stats.Letters++;
if (char.IsUpper(c)) stats.UpperCase++;
else stats.LowerCase++;
}
else stats.Special++;
}
return stats;
}
// 使用:
var stats = Analyze("Abc123!@#");
Console.WriteLine($"大寫:{stats.UpperCase} 小寫:{stats.LowerCase} 數字:{stats.Digits} 特殊:{stats.Special}");
| 錯誤寫法 | 問題 | 正確寫法 |
|---|---|---|
char.IsDigit(str) |
IsDigit 只接受 char,字串會隱含轉換失敗 |
str.All(char.IsDigit) 或 int.TryParse |
int.Parse(str) 無 try-catch |
非數字拋 FormatException,效能極差 |
int.TryParse(str, out _) |
str.All(c => c >= '0' && c <= '9') |
空字串回傳 true (邏輯漏洞) |
!string.IsNullOrEmpty(str) && str.All(...) |
char.IsNumber(c) 當作 IsDigit |
IsNumber 包含分數、羅馬數字、全形數字等 |
確認需求:僅 0-9 用 IsDigit 或 c >= '0' && c <= '9' |
| 正則未預編譯高頻呼叫 | 每次實例化 Regex 物件,GC 壓力大 | static readonly Regex _digitRegex = new(@"^\d+$", RegexOptions.Compiled); |
// 環境:.NET 8, Release, x64
// 測試字串:"1234567890" (純數字)
Method Mean (ns) Allocated
-------------------------------------------------------
int.TryParse 45.2 0 B
Manual Loop (foreach) 12.8 0 B
str.All(char.IsDigit) 18.5 0 B
Regex (Compiled) 85.3 72 B
Regex (Non-compiled) 420.1 240 B
**結論**:高頻路徑用 int.TryParse (需值) 或手動迴圈/ All (僅驗證);正則保留給複雜模式。
public static bool ContainsFullWidthDigit(string s)
{
foreach (char c in s)
if (c >= '\uFF10' && c <= '\uFF19') // 0-9
return true;
return false;
}
// 統一正規化:全形轉半形
public static string NormalizeDigits(string s)
{
char[] buf = s.ToCharArray();
for (int i = 0; i < buf.Length; i++)
if (buf[i] >= '\uFF10' && buf[i] <= '\uFF19')
buf[i] = (char)(buf[i] - '\uFF10' + '0');
return new string(buf);
}
C# 判斷字串數字/字母特性,**首選 int.TryParse/double.TryParse (需轉換值)**、**次選 str.All(char.IsDigit) (僅驗證純數字)**、**複雜規則用預編譯 Regex**。切記:空字串邊界、全形/半形區分、Unicode 字母範圍、高頻路徑避免例外與 Regex 實例化。掌握這些細節,即能寫出正確、高效、可維護的輸入驗證代碼。