我试图通过重载+运算符来实现合并客户帐户的功能 .. 我最初在bankaccounts列表中输入输入,然后将list传递给函数的参数,该函数返回包含BankAccounts对象的列表。 到目前为止,我已经获得了包含与特定客户相关的所有帐户信息的列表
但我必须使用重载+添加列表项但无法这样做..这是我的课程和主要代码... KINDLY帮助......
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();
}
}
}
答案 0 :(得分:1)
答案:为BankAccounts和BankAccounts定义运营商+: - )
答案 1 :(得分:1)
您已将运营商定义为BankAccounts
和List<BankAccounts>
;但是在您的示例代码中,您尝试将两个BankAccounts
对象添加到一起。
重新定义运算符以仅添加两个实例,或更改用法以将列表添加到实例。