未处理的formatExcepton

本文关键字:formatExcepton 未处理 | 更新日期: 2023-09-27 18:16:00

我是c#新手。我想做一个计算器,但我有FormatException抛出:

private void operator_click(object sender, EventArgs e) {
  Button button = (Button) sender;
  operationperformed = button.Text;
  result = Double.Parse(textBox1.Text);  // <- here I have the exception thrown
  b = true; 
}

未处理的formatExcepton

我建议用double.TryParse代替double.Parse:

private void operator_click(object sender, EventArgs e) {
  double v;
  if (!double.TryParse(textBox1.Text, out v)) {
    // textBox1.Text doesn't contain double, e.g. "bla-bla-bla"
    //TODO:put a warning/error message here
    return; 
  }
  // textBox1.Text has a double value which is v
  operationperformed = (sender as Button).Text;
  result = v;
  b = true; 
}