尝试catch - c#: int.解析不能正常工作

本文关键字:常工作 工作 不能 catch int 尝试 | 更新日期: 2023-09-27 17:49:21

我在c#中实现了以下方法,检查用户输入的号码是否是10位数字。对于最多10位的输入数字,它可以正常工作。但是,当我输入大于10位的数字时,它打印给定的字符串不代表数字而不是

我知道我可以使用正则表达式匹配做同样的事情,但我只想通过抛出异常来做到这一点。如有任何帮助,不胜感激。

    public static bool CheckContactNo(string ContactNo)
    {
        try
        {
            int Number = int.Parse(ContactNo);
            int IsZero = ContactNo.Length == 10 ? 1 : 0;
            //Console.WriteLine("{0}",IsZero);
            int somenum = 1/ IsZero;
            return true;
        }
        catch(DivideByZeroException)
        {
            Console.WriteLine("The length of the Contact No. is not 10");
            return false;
        }
        catch (Exception)
        {
            Console.WriteLine("Given string does not represent a number");
            return false;
        }
    }

尝试catch - c#: int.解析不能正常工作

32位int不能容纳10位整位数,其最大值为2,147,483,647

换句话说,int.Parse检测到int将溢出,并给出该错误。

MaxValue为2,147,483,647。您将无法解析大于int.maxvalue.

的数字

除了Joachim的答案(解决方案是使用Int64),我也不会使用异常(如DivZero)以这种方式控制流,而是更喜欢使用验证,如TryParse来确定值是否为数字:

if (contactNo.Length != 10)
{
    Console.WriteLine("The length of the Contact No. is not 10");       
}
else
{
    long contactLong;
    if (Int64.TryParse(ContactNo, out contactLong)
    {
        return true;
    }
    else
    {
        Console.WriteLine("Given string does not represent a number");
    }
}
return false;

可以使用Int64代替int

This(2,147,483,647)是Int32的最大值,所以int。对此进行内部检查你可以用Int64。解析