c#添加时遇到问题

时间:2013-12-03 16:48:49

标签: c# addition

我是新手,所以请耐心等待,我现在加入时遇到一些麻烦。我试图这样做,所以每次点击按钮,它总共增加5。任何人都可以帮助我吗?

这是CashBox类:

public string cash1()
{
   return "5";
}

这是点击按钮时的代码:

CashBox fivepence;
fivepence = new CashBox();
txtMoney.Text = txtMoney.Text + fivepence.cash1();
total1 = total1 + double.Parse(txtMoney.Text);

如果按下按钮三次,结果是555而不是15。 任何帮助将不胜感激!!

2 个答案:

答案 0 :(得分:3)

您应该按相反的顺序执行操作:首先进行添加,然后使用结果更新UI。首先,将cash1更改为return 5(整数,而不是字符串)。然后:

// do the math
var subtotal = double.Parse(txtMoney.Text) + fivepence.cash1();

// update the user interface
txtMoney.Text = subtotal.ToString();

// update total1, whatever that is
total1 += subtotal;

答案 1 :(得分:1)

您需要返回整数5,而不是字符串。您当前的方法将返回字符串,结果将是字符串连接而不是整数加法。尝试:

  public int cash1()
  {
      return 5;
  }

然后:

txtMoney.Text = (double.Parse(txtMoney.Text) + fivepence.cash1()).ToString();
total1 = total1 + double.Parse(txtMoney.Text); //or total1 += double.Parse(txtMoney.Text);