有没有更好的方法来确定字符串是否可以是try/catch以外的整数?

Edw*_*uay 6 c# validation

我需要一个函数来简单地检查一个字符串是否可以转换为一个有效的整数(用于表单验证).

在搜索之后,我最终使用了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)

  • 而long.TryParse也适用于64位值. (2认同)

Jan*_*ich 11

这可能不会快得多,但至少它看起来更干净(没有异常处理):

 public static bool IsAValidInteger(string strWholeNumber)
 {
     int wholeNumber;
     return int.TryParse(strWholeNumber, out wholeNumber);
 }
Run Code Online (Sandbox Code Playgroud)

  • 我怀疑.我正要测试它...但现在没有意义,因为自从Jon Skeet确认了它:-) (3认同)
  • 实际上,对于反复获取无效字符串的情况,它会明显加快. (2认同)

Dan*_*ner 6

您正在寻找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)


Jos*_*ger 5

Int32.TryParse