在C#中,try-catch是否可用于数字测试?

我听说使用exception捕获不是数字测试的推荐做法。

例如:

bool isnumeric try { int i = int.parse(textbox1.text); isnumeric = true; } catch {isnumenric=false} 

还有其他方法可以测试C#中的数字吗?

是的尝试使用

 int i; bool success = Int32.TryParse(textBox1.text, out i); 

TryParse方法基本上可以完成上面的操作。

使用内置的TryParse

例如

 int number; bool result = Int32.TryParse(value, out number); 

是。 使用int.TryParse,double.TryParse等,它们都返回一个布尔值。

或者,有一个隐藏在VB程序集中的IsNumeric函数(在Microsoft.VisualBasic.dll中的Microsoft.VisualBasic命名空间中),您也可以从C#代码中调用它:

bool Microsoft.VisualBasic.Information.IsNumeric(value)

的TryParse()

 int i; if(Int32.TryParse(someString,out i)) { //now use i because you know it is valid //otherwise, TryParse would have returned false } 
 int result = -1; bool isNumeric = Int32.TryParse(text, out result); 

如果数字是数字,则isNumeric为true,否则为false; 如果数字是数字,则结果将具有数字的数字值。

bool TryParse(string,out int)

如果它能够解析整数,它将返回一个为true的bool,而out参数将包含整数(如果它在解析时成功)。

如果您只需要进行数字测试而不需要整数,则可以使用下面的函数。 这比Int32.TryParse(…)方法快。

编辑Barry Fandango:现在处理负数。 这仅用于测试整数。

  public static bool IsNumber(string s) { if (s == null || s.Length == 0) { return false; } if (s[0] == '-') { for (int i = 1; i < s.Length; i++) { if (!char.IsDigit(s[i])) { return false; } } } else { foreach (char c in s) { if (!char.IsDigit(c)) { return false; } } } return true; } 

如果你想要整数,那么Int32.TryParse(…)就是你想要的其他Information.IsNumeric(…)(来自Microsoft.VisualBasic.dll),如果你不关心实际的整数是什么。