繁体   English   中英

C#:int.Parse无法正常工作

[英]c# : int.Parse not working correctly

我在c#中实现了以下方法,以检查用户输入的数字是否为10位数字。 最多输入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;
        }
    }

一个32位int不能容纳10个全数字,其最大值2,147,483,647

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

Int32.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

这(2,147,483,647)是Int32的最大值,因此int.Parse在内部对此进行检查您可以使用Int64.Parse

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM