我试图通过重载 + 运算符来实现合并客户帐户的功能。我最初在银行帐户列表中输入,然后将列表传递给函数的参数,该函数返回包含 BankAccounts 对象的列表。到目前为止,我已经获得了包含与特定客户相关的所有帐户信息的列表
但我必须使用重载+ 添加列表项但无法这样做..这是我的课程和主要代码......请帮助......
namespace OpOverload{class BankAccounts
{
private string title;
List<BankAccounts> bankList = new List<BankAccounts>();
private double balance;
internal List<BankAccounts> BankList
{
get { return bankList; }
set { bankList = value; }
}
public double Balance
{
get { return balance; }
set { balance = value; }
}
public string Title
{
get { return title; }
set { title = value; }
}
public void input()
{
BankAccounts[] banks = new BankAccounts[3] { new BankAccounts(), new BankAccounts(), new BankAccounts() };
int i = 0;
do
{
Console.WriteLine("Account Title?: ");
banks[i].Title = Console.ReadLine();
Console.WriteLine("Account Balance Deposited?: ");
banks[i].Balance = Convert.ToInt32(Console.ReadLine());
bankList.Add(banks[i]);
++i;
} while (i <= 2);
}
public List<BankAccounts> setTogether(string title1, List<BankAccounts> blist)
{
List<BankAccounts> sameName2gther = new List<BankAccounts>();
foreach (BankAccounts item in blist)
{
if (item.Title == title1)
{
sameName2gther.Add(item);
}
}
return sameName2gther;
}
public static BankAccounts operator +(BankAccounts b1,List<BankAccounts> blist)
{
BankAccounts ba = new BankAccounts();
foreach (BankAccounts item in blist)
{
ba.balance = ba.balance + item.Balance;
ba.title = item.Title;
}
return ba;
}
}
}
主要代码是:
namespace OpOverload{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("===========Merge Accounts============");
List<BankAccounts> customList = new List<BankAccounts>();
BankAccounts b1 = new BankAccounts();
BankAccounts result = new BankAccounts();
b1.input();
foreach (BankAccounts item in b1.BankList)
{
Console.WriteLine(item.Title + "-->" + item.Balance);
}
customList = b1.setTogether("sana", b1.BankList);
foreach (BankAccounts item in customList)
{
Console.WriteLine(item.Title + "-->" + item.Balance);
}
for (int i = 0; i < customList.Count; i++)
{
result = result + customList[i];
}
Console.ReadLine();
}
}
}