【问题标题】:Is there any way I can simplify this?有什么办法可以简化这个吗?
【发布时间】:2019-02-04 18:51:53
【问题描述】:

我有两个要相乘的标签(工资和工时)。当用户没有输入数字时,我希望显示一个错误框,但我只能找出最简单的方法是制作两个 if 语句并这样做。任何帮助都会很棒。

    private void btnCalc_Click(object sender, EventArgs e)
    {
        double hours = Double.Parse(tbxHours.Text);
        double pay = Double.Parse(tbxPay.Text);

        if (Double.TryParse(tbxPay.Text,  out pay))
            {
            double result = hours * pay;
            MessageBox.Show($" total amount is {result} ", "Click Event",
            MessageBoxButtons.OKCancel, MessageBoxIcon.Information);

        }
        else
        {
            MessageBox.Show($"You must enter a number", "Input Error",
        MessageBoxButtons.OK, MessageBoxIcon.Error);

            tbxPay.Clear();

        }


        if (Double.TryParse(tbxHours.Text, out hours))
        {
            double result = hours * pay;
        }
        else
        {
            MessageBox.Show($"You must enter a number", "Input Error",
        MessageBoxButtons.OK, MessageBoxIcon.Error);

            tbxHours.Clear();

        }
    }

【问题讨论】:

  • 你解析了两次。

标签: c# visual-c#-express-2010


【解决方案1】:

每个控件只需要解析一次。这是一个简化,您可以重复使用多个包含数字作为文本的控件。

private void btnCalc_Click(object sender, EventArgs e)
{
    if (TryParseFromTextBox(tbxHours, out double hours) && 
        TryParseFromTextBox(tbxPay, out double pay))
    {
        double result = hours * pay;
        MessageBox.Show($" total amount is {result} ", "Click Event", 
                        MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
    }
}

public bool TryParseFromTextBox(TextBox control, out double value)
{
    if (!double.TryParse(control.Text, out value))
    {
        MessageBox.Show($"You must enter a number in {control.Name}", "Input Error", 
                        MessageBoxButtons.OK, MessageBoxIcon.Error);

        control.Clear();
        return false;
    }
    return true;
}

需要考虑的一些额外事项。

  • 是否应该专注于数字解析失败的控件?
  • 如果这些文本框中没有有效数字,您的btnCalc 是否应该可以点击?

【讨论】:

  • 哇!谢谢!我试图弄清楚如何将两个变量添加到我忘记了 && 的 if 语句中
猜你喜欢
  • 2015-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-23
  • 1970-01-01
相关资源
最近更新 更多