我有两个帐户可以合并到一个新的支票帐户中。这应该创建具有 2 个余额总和的新支票帐户。我有一个代码:public void ConsolidateAccounts(int accountNumber1, int accountNumber2) { if (accountNumber1 == accountNumber2) { throw new InvalidOperationException("Same accounts can not be consolidated"); } else { int newAccountNumber = 0; var newAccount = new Checking(newAccountNumber, (accountNumber1.balance + accountNumber2.balance)); }}这是我的帐户类:class Account{ private readonly int _accountNumber; protected double balance; public AccountStatus Status { get; set; } public Account() { } public Account(int accountNumber, double balance) { this._accountNumber = accountNumber; this.balance = balance; } public double Balance { get; private set; }}我在帐户类中有更多方法,但我不需要它们来回答这个问题。问题是,如何为 accountNumber1 和 accountNumber2 指定余额,因为余额以红色突出显示。我不确定如何访问余额。(accountNumber1.balance + accountNumber2.balance)
1 回答
烙印99
TA贡献1829条经验 获得超13个赞
问题是您将一个int(我假设是帐户 ID)传递给您的函数,而不是Account实例。
我们需要做的第一件事是在您的Account类中公开帐户 ID :
public int AccountId => _accountNumber;
然后我们需要修复这个Balance属性(它不是由构造函数设置的):
public double Balance
{
get => this.balance;
private set => this.balance = value;
}
然后我们可以像这样更改方法:
public void ConsolidateAccounts(Account account1, Account account2)
{
if (account1.AccountNumber == account2.AccountNumber)
{
throw new InvalidOperationException("Same accounts can not be consolidated");
}
else
{
int newAccountNumber = 0;
var newAccount = new Checking(newAccountNumber, (account1.Balance + account2.Balance));
}
}
- 1 回答
- 0 关注
- 191 浏览
添加回答
举报
0/150
提交
取消