【发布时间】:2023-03-26 20:07:01
【问题描述】:
我是 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 Instructions 要求我将 Balance 设置为只读属性。如果我被允许添加一个 setter 不会有问题。
-
TLDR;我认为你需要类似
private decimal defaultBalance; -
为什么您的 Balance 获取器返回的是 defaultBalance 而不是实际余额?此外,您尝试设置 account.Balance 的值在线您标记了哪个。您应该将 acc.Balance 解析到文本字段中
-
考虑到程序的性质,为
Balance设置一个setter 是不好的设计。对Balance的任何更改都应该是存款的结果;提款;转让;借方;Account对象的信用 和其他形式的交易
标签: c# methods constructor readonly