我有一個變量,我可以從這段代碼中訪問。該變量是:平衡
這是代碼的從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