-1

我试图通过重载 + 运算符来实现合并客户帐户的功能。我最初在银行帐户列表中输入,然后将列表传递给函数的参数,该函数返回包含 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();
    }
}

}

4

2 回答 2

1

答案:为 BankAccounts 和 BankAccounts 定义运算符 + :-)

于 2012-06-06T15:13:13.547 回答
1

您将运算符定义为采用 aBankAccounts和 a List<BankAccounts>; 但是在您的示例代码中,您尝试将两个BankAccounts对象加在一起。

重新定义运算符以仅添加两个实例,或更改您的用法以将列表添加到实例。

于 2012-06-06T15:14:00.213 回答