我是C#的新手,目前正在研究方法和构造函数,以创建一个简单的银行取款和存款计划,以计算之后的余额。
我对这些给我的指示感到困惑,或者我做错了什么。我似乎无法弄明白。我想将Balance字段设置为只读字段时,将初始默认余额设置为$ 1000。
我遇到的主要问题是我正在尝试为只读" Balance"设置一个构造函数。领域。 C#说我不能调用只读方法。如果有人能帮助我,我在下面发布了我的代码。提前谢谢。
Account.cs
class Account
{
public const double defaultBalance = 1000;
private double _amount;
public double balance;
public double Balance
{
get { return defaultBalance; }
}
public double Amount
{
get
{
return _amount;
}
set
{
if (value < 0)
{
throw new ArgumentException("Please enter an amount greater than 0");
}
else
{
_amount = value;
}
}
}
public double doDeposit()
{
balance += _amount;
return balance;
}
public double doWithdrawl()
{
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();
private void btnWithdraw_Click(object sender, EventArgs e)
{
try
{
acc.Amount = double.Parse(txtAmount.Text);
//Error in the line below. "Property cannot be assigned to -- it is read only
//Trying to set the initial balance as $1000 using constructor from 'Account' class
acc.Balance = double.Parse(lblBalance.Text);
lblBalance.Text = acc.doWithdrawl().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 = double.Parse(txtAmount.Text);
lblBalance.Text = acc.doDeposit().ToString("C");
}
catch (FormatException ex)
{
MessageBox.Show(ex.Message);
}
catch (ArgumentException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}
}
答案 0 :(得分:3)
Amount
属性,我的意思是; DoWithdraw(decimal amount)
和DoDeposit(decimal amount)
Balance
,但只能通过课程方法修改它。答案是使用自动实现的属性; public decimal Balance { get; private set; }
Withdraw
和Deposit
然后,您的Account
源代码将是:
class Account {
public decimal Balance { get; private set; }
public Account(decimal initialBalance) {
if(initialBalance < 0)
throw new ArgumentOutOfRangeException("The initial balance must be greater or equals to 0");
this.Balance = initialBalance;
}
public bool TryDeposit(decimal amount) {
if(amount <= 0)
return false;
this.Balance += amount;
return true;
}
public bool TryWithdraw(decimal amount) {
if(amount <= 0 || this.Balance - amount < 0)
return false
this.Balance -= amount;
return true;
}
}
答案 1 :(得分:0)
1)请使用以下类别将其更改为控制台应用程序(存款,取款,支票余额,更改密码)
2)请使用所有类OOP支柱将其更改为控制台类的应用程序(存款,提款,支票余额,更改销)