如何处理整数异常



我正在尝试处理输入字符串而不是整数的情况。例如

newCustomer.PhoneNum = Convert.ToInt32(Console.ReadLine());
if (newCustomer.PhoneNum < 0 || newCustomer.PhoneNum > 10000000000 || newCustomer.PhoneNum.GetType() != typeof (int))
{
    throw new CustomException(newCustomer.PhoneNum.ToString());
}

显然,if的最后一个条件是不对的,但我没有想法。

string text1 = "x";
int num1;
if (!int.TryParse(text1, out num1))
{
    // String is not a number.
}

您需要首先使用 int 检查输入的内容。TryParse,如果它是有效的整数,则将值放入out参数中,如果不是,则返回false。

int phoneNumber;
string input = Console.ReadLine();
if (!int.TryParse(input, out phoneNumber))
{
    throw new CustomException(input);
}
else if (phoneNumber < 0 || phoneNumber > 10000000000
{
    throw new CustomException(phoneNumber);
}
newCustomer.PhoneNum = phoneNumber;

显然,我刚刚重现了您在示例中指定的验证逻辑,但它似乎有点简单,可能会抛出完全有效的电话号码。

如果您正在使用原始数据,则可以使用 int。TryParse() 如前所述。

但是,如果您尝试验证更复杂的规则,则可能需要使用类似 FluentValidation nuget 包的东西,我非常喜欢它。它使验证成为一种更愉快的体验:)

http://fluentvalidation.codeplex.com/

或者,如果您使用的是 ASP.Net 或 MVC 之类的东西,则内置了验证引擎。在 MVC 中,您可以使用模型数据注释非常轻松地(并且以有组织的方式)执行客户端和服务器端验证。查看不显眼的验证。

    int i;
    string n=textbox1.Text;
    bool success = int.TryParse(n, out i);
//if the parse was successful, success is true
    if(success)
    {
    //do ur code
    }
    else
    {
     throw new CustomException(newCustomer.PhoneNum.ToString());
    }

相关内容

最新更新