我是C#的新手,并且已经开始研究这个项目了。我修复了以前的问题并完成了一个工作程序。但是,我现在陷入了一个新问题。我有一个提取或存款的银行业务计划,并增加了初始余额。但是,在初始存款或取款后,我无法更新到新的余额。
TL; DR:初始余额= 1000.存款为100.新余额= 1100.另外存款100,不会更新,余额将保持在1100.
Account.cs
namespace Account_Teller
{
class Account
{
private decimal _amount;
public decimal balance;
public decimal Balance { get; }
public Account (decimal pBalance)
{
this.Balance = pBalance;
}
public decimal Amount
{
get
{
return _amount;
}
set
{
if (value < 0)
{
throw new ArgumentException("Please enter an amount greater than 0");
}
else
{
_amount = value;
}
}
}
public decimal Deposit()
{
balance = Balance + _amount;
return balance;
}
public decimal Withdrawl()
{
balance = Balance - _amount;
if (balance < 0)
{
throw new ArgumentException("Withdrawing " + _amount.ToString("C") + " would leave you overdrawn!");
}
return balance;
}
}
}
Main.cs
namespace Account_Teller
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Account acc = new Account(1000);
private void btnWithdraw_Click(object sender, EventArgs e)
{
lblBalance.Text = acc.Balance.ToString("C");
try
{
acc.Amount = decimal.Parse(txtAmount.Text);
lblBalance.Text = acc.Withdrawl().ToString("C");
}
catch (FormatException ex)
{
MessageBox.Show(ex.Message);
}
catch (ArgumentException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}
private void btnDeposit_Click(object sender, EventArgs e)
{
try
{
acc.Amount = decimal.Parse(txtAmount.Text);
lblBalance.Text = acc.Deposit().ToString("C");
}
catch (FormatException ex)
{
MessageBox.Show(ex.Message);
}
catch (ArgumentException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
lblBalance.Text = acc.Balance.ToString("C");
}
}
}
答案 0 :(得分:1)
您的代码中没有任何内容将属性Balance
绑定到字段balance
。就C#而言,它们是两个独立的变量。
您的Balance
应该定义为:
public decimal Balance { get; private set; }
那么你根本就没有balance
字段。
你班上的其他人应该是这样的:
public class Account
{
public decimal Balance { get; private set; }
public Account(decimal balance)
{
this.Balance = balance;
}
public void Deposit(decimal amount)
{
if (amount < 0m)
{
throw new ArgumentException("Please enter an amount greater than 0");
}
this.Balance = this.Balance + amount;
}
public void Withdraw(decimal amount)
{
if (this.Balance - amount < 0m)
{
throw new ArgumentException("Withdrawing " + amount.ToString("C") + " would leave you overdrawn!");
}
this.Balance = this.Balance - amount;
}
}
这将是此代码的更典型的实现。
然后您将编写此类代码以使用该类:
acc.Withdraw(decimal.Parse(txtAmount.Text));
lblBalance.Text = acc.Balance.ToString("C");
答案 1 :(得分:-1)
因为您没有在余额和余额之间设置约束。有一点,不要将平衡公开为公共
BiomeType playerCurrentBiomeType;
LocationType playerCurrentLocationType;
LoadLevel(myDictionary[playerCurrentBiomeType][playerCurrentLocationType]);
//ex. myDictionary[BiomeType.Jungle][LocationType.CapitalCity]
//ex. myDictionary[BiomeType.Desert][LocationType.CapitalCity]
//ex. myDictionary[BiomeType.Desert][LocationType.City3]