我听说使用异常捕获不是数字测试的推荐做法.
例如:
bool isnumeric
try
{
int i = int.parse(textbox1.text);
isnumeric = true;
}
catch {isnumenric=false}
Run Code Online (Sandbox Code Playgroud)
还有其他方法可以测试C#中的数字吗?
Nic*_*rdi 15
是的尝试使用
int i;
bool success = Int32.TryParse(textBox1.text, out i);
Run Code Online (Sandbox Code Playgroud)
该的TryParse方法基本上没有,你在上面做什么.
And*_*ngs 10
使用内置的TryParse
例如
int number;
bool result = Int32.TryParse(value, out number);
Run Code Online (Sandbox Code Playgroud)
是.改为使用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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3290 次 |
| 最近记录: |