C# Text to int-当我插入数字以外的内容时,我的程序崩溃

C# Text to int-当我插入数字以外的内容时,我的程序崩溃,c#,.net,C#,.net,我有一个C#.NET WF中的简单计算器。但当我在编辑框中插入数字以外的内容时,我的程序崩溃了。我应该如何避免这次撞车 private void doMath() { int n1 = Int32.Parse(editBox1.Text); int n2 = Int32.Parse(editBox2.Text); String o = operation.Text; switch(o) { case "+": result.Text =

我有一个C#.NET WF中的简单计算器。但当我在编辑框中插入数字以外的内容时,我的程序崩溃了。我应该如何避免这次撞车

private void doMath()
{
    int n1 = Int32.Parse(editBox1.Text);
    int n2 = Int32.Parse(editBox2.Text);

    String o = operation.Text;

    switch(o)
    {
        case "+": result.Text = (n1 + n2).ToString();
            break;
        case "-": result.Text = (n1 - n2).ToString();
            break;
        case "*": result.Text = (n1 * n2).ToString();
            break;
        case "/": result.Text = (n1 / n2).ToString();
            break;
        case "%": result.Text = (n1 % n2).ToString();
            break;
        default: result.Text = "No operator selected.";
            break;
    }
}//end doMath

private void editBox1_TextChanged(object sender, EventArgs e)
{
    doMath();
}

Int32.Parse
依赖于一个事实,即您有一个int开头。因此,尝试解析
123
将有效,但尝试解析
123e
将引发异常

使用
Int32.TryParse
将要求输出
int
,但如果您传递的不是int的内容,则会处理异常,并且操作返回将告诉您是否成功。 如果是,则在out参数中获得值,如果不是,则该类型将具有默认值(在本例中为0)

试试这个:

int n1 = 0;
Int32.TryParse(editBox1.Text,out n1);
int n2 = 0;
Int32.TryParse(editBox2.Text,out n2);

或者,您可以捕获此异常:

try{

    int n1 = Int32.Parse(editBox1.Text);
    int n2 = Int32.Parse(editBox2.Text);
}catch(FormatException e){
    result.Text = e.toString() + "\nEnter numerical value only";
}

这里有几个答案是正确的,但我要补充一点说明:

int firstNum;
Var isFirstNumeric = Int32.TryParse(editBox1.Text, out firstNum);
int secondNum;
Var isSecondNumeric = Int32.TryParse(editBox2.Text, out secondNum);
现在,您可以使用
firstNum
secondNum
,就像您在原始示例中使用n1和n2一样,但您应该首先测试有效性:

if(!isFirstNumeric)
{ 
    ShowErrorMsg("The first value is not a valid number!");
}
else if(!isSecondNumeric)
{ 
    ShowErrorMsg("The second value is not a valid number!");
}
else
{
    // We know both numbers are valid.
    // Place your switch here and calculate as before...
}

请查看。但是如果可以使用
int.TryParse
,请不要使用异常处理。无效的用户输入不是例外情况。当然。它只是一种选择,出于某种原因,您不能使用
int.TryParse
if(!isFirstNumeric)
{ 
    ShowErrorMsg("The first value is not a valid number!");
}
else if(!isSecondNumeric)
{ 
    ShowErrorMsg("The second value is not a valid number!");
}
else
{
    // We know both numbers are valid.
    // Place your switch here and calculate as before...
}