之前写的方法,使用try catch来处理
如果能捕获异常就说明问题
public bool CheckLegal() { double number; bool flag = true; try { foreach (Control c in groupBox1.Controls) { if (c is TextBox) { number = Convert.ToDouble(c.Text.Trim()); } } foreach (Control c in groupBox2.Controls) { if (c is TextBox) { number = Convert.ToDouble(c.Text.Trim()); } } } catch { flag = false; } return flag; }
第二种方法,使用double的tryParse方法,根据返回值来处理
麻烦的地方在于,需要对每一次的处理结果进行判断
public bool CheckLegal() { bool flag; double number; foreach (Control c in groupBox1.Controls) { if (c is TextBox) { flag = double.TryParse(c.Text.Trim(), out number); if (flag == false) { return false; } } } foreach (Control c in groupBox2.Controls) { if (c is TextBox) { flag = double.TryParse(c.Text.Trim(), out number); if (flag == false) { return false; } } } return true; }