我是C#的新手,目前正在使用方法和構造函數創建一個簡單的銀行取款和存款程序來計算餘額後。銀行取款和存款程序C#
我對這些給我的指示感到困惑,或者我做錯了什麼。我似乎無法弄清楚。我試圖將初始默認餘額設置爲$ 1000,同時將餘額字段設置爲只讀字段。
我遇到的主要問題是我試圖爲只讀的「平衡」字段設置構造函數。 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);
}
}
}
你不必在你的'Balance'屬性的設置。 – Steve
@Steve指令要求我將Balance設置爲只讀屬性。如果我被允許添加一個setter,那不會是個問題。 – hyang24
TLDR;我想你需要像'private decimal defaultBalance;' – Timeless