我需要一个函数来简单地检查一个字符串是否可以转换为一个有效的整数(用于表单验证).
在搜索之后,我最终使用了2002年的一个函数,该函数使用C#1(下面).
但是,在我看来,虽然下面的代码有效,但是使用try/catch是为了捕获错误而不是确定一个值.
在C#3中有更好的方法吗?
public static bool IsAValidInteger(string strWholeNumber)
{
try
{
int wholeNumber = Convert.ToInt32(strWholeNumber);
return true;
}
catch
{
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
John的回答帮助我构建了我没有try/catch的功能.在这种情况下,空格文本框在我的表单中也被视为有效的"整数":
public static bool IsAValidWholeNumber(string questionalWholeNumber)
{
int result;
if (questionalWholeNumber.Trim() == "" || int.TryParse(questionalWholeNumber, out result))
{
return true;
}
else
{
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
Joh*_*ers 33
if (int.TryParse(string, out result))
{
// use result here
}
Run Code Online (Sandbox Code Playgroud)
Jan*_*ich 11
这可能不会快得多,但至少它看起来更干净(没有异常处理):
public static bool IsAValidInteger(string strWholeNumber)
{
int wholeNumber;
return int.TryParse(strWholeNumber, out wholeNumber);
}
Run Code Online (Sandbox Code Playgroud)
您正在寻找Int32.TryParse().
public void Foo(String input)
{
Int32 number;
if (Int32.TryParse(input, out number))
{
DoStuff(number);
}
else
{
HandleInvalidInput(input);
}
}
Run Code Online (Sandbox Code Playgroud)
在您的具体情况下,我将使用以下内容.
public static Boolean IsValidInt32(String input)
{
Int32 number;
return Int32.TryParse(input, out number);
}
Run Code Online (Sandbox Code Playgroud)