简体   繁体   中英

C# storing data from input to arraylist inside Class

I have got a class called Customers with an Arraylist inside to store information about the Customer Accounts; then inside Accounts class I have an Arraylist to hold the Transactions.

My question is, how would I go about saving to the Arraylist found within the Customer Class. It doesnt seem like I can access it.

    if (allInputOK)
    {
        //create Account
        Account temp = new Account(tempAccSortCode, tempAccNumber, tempAccNickName, tempAccDate, tempAccCurBal, tempAccOverDraft, tempNumTrans);

        //add to array
        //Need to add here.


        //finish up
        MessageBox.Show("Success Account added ");
        resetForm();
    }

This is my method on a form to add to the Arraylist. It first checks the input is OK, then creates a new Account called temp (Account is the Class name). Then how do I go about saving this inside of the Arraylist inside the Class Account?

Thanks.

public class Account
{
}

public class Customer
{
    public ArrayList Accounts
    {
        get;
        private set;
    }

    public Customer()
    {
        Accounts = new ArrayList();
    }

    public void AddAccount(Account account)
    {
        // if account is valid add it to the local collection
        Accounts.Add(account);
    }
}

Then in your code:

if (allInputOK)
{
    //create Account
    Account temp = new Account(tempAccSortCode, tempAccNumber, tempAccNickName, tempAccDate, tempAccCurBal, tempAccOverDraft, tempNumTrans);

    //add to array
    _customer.AddAccount(temp);

    //finish up
    MessageBox.Show("Success Account added ");
    resetForm();
}

Building on Swaff's answer earlier, just make your Accounts ArrayList private and expose the AddAccount functionality:

public class Customer {
  private ArrayList _accounts = new ArrayList();

  ...

  public void AddAccount(Account theAccount){
    //do some validation...if OK, then add to ArrayList...
    _accounts.Add(theAccount);
  }

  //you'll also need facade methods to retrieve accounts
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM