我有两个帐户,可能会合并到一个新的支票帐户中。这将创建一个新的带有两个余额之和的支票帐户。 我有一个代码:
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)
答案 0 :(得分:1)
问题是您正在将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));
}
}