我有一个变量,我可以从这段代码中访问。该变量是:平衡
这是代码的从Form3一个片段:在C中更新全局变量#
public static int balance = 0;
private void button1_Click(object sender, EventArgs e)
{
int deposit=int.Parse(textBox1.Text);
if (deposit == 0)
{
MessageBox.Show("Please enter a value greater than 0");
}
else
{
balance = balance + deposit;
MessageBox.Show("Thank you, your balance has been updated.");
}
}
现在,当我想存钱,我要平衡更新,这样,当我从另一种形式查看它需要成为编辑的余额(余额更新为存款金额)。我很努力取得平衡,以更新,它的工作原理,当我在更新,但后来当我走在另一种形式来查看它,它仍然显示余额为0
int bal = Form3.balance;
public int Balance()
{
//MessageBox.Show("Your current balance is: "+bal);
return bal;
}
private void button1_Click(object sender, EventArgs e)
{
/*if (bal < 0)
{
MessageBox.Show("You don't have enough cash in your account, please deposit some money before you can continue");
}
else*/
if (bal < 5)
{
MessageBox.Show("Please credit your account before you can withdraw");
}
else
{
MessageBox.Show("Please wait for your £5 to be dispensed");
bal = bal - 5;
Balance();//I thought if I returned the balance variable from a different method that it would still update regardless
//I am struggling making sure that the balance gets updated.
}
}
我该怎么办表单确保我的平衡变量在全球更新?
你的'Balance'方法*只返回'bal'。它不会做任何事情 - 它当然不会改变“平衡”。你正在调用一个无副作用的方法,并忽略返回值,它总是*一个不好的迹象。就我个人而言,我会尽量避免让一个全局变量开始,说实话。 – 2013-05-11 15:40:18