关注开源代码的实际应用
VB.NET中有大量使用方便的函数在C#中却需要开发者自己实现,IsNumeric便是其中一个,下面提供四种实现方法:
实现一、通过Int32.Parse
- static bool IsNumeric(string s)
- {
- try
- {
- Int32.Parse(s);
- }
- catch
- {
- return false;
- }
- return true;
- }
实现二、通过Double.TryParse(C# 2.0及后续版本)
- static bool IsNumeric(string s)
- {
- double t;
- return double.TryParse(s,out t);
- }
实现三、通过正则表达式
- bool IsNumeric(string value)
- {
- Regex regxNumericPatters = new Regex("[^0-9]");
- return !regxNumericPatters.IsMatch(value);
- }
实现四、逐个字符判断
- static bool IsNumeric(string numberString)
- {
- foreach (char c in numberString)
- {
- if (!char.IsNumber(c))
- return false;
- }
- return true;
- }