首页 > 解决方案 > C# 在类中管理列表的问题

问题描述

晚上好,

只是为了有一点背景,我几个月前才开始使用 C#,并且我正在使用 C# 作为作业制作一个银行应用程序。

我有 2 个类:从抽象类Person继承的CustomerBank EmployeeAccount类(基本上是储蓄、当前等)继承自 Customer 类。

UML 我只保留了属性,因为其余的与接下来的内容无关。我的问题是我似乎无法理解我在AllAccounts列表中重新组合客户的所有帐户时做错了什么。

事情是这样的,我主要是在 Customer 类中操作AllAccounts 列表,一旦它退出任何方法,它就不会保存任何更改。

我通过在方法内部和外部显示列表的长度来检查(让它在 program.cs 或 Customer.cs 中)。默认情况下,该方法创建 2 个帐户,因此显示的第一个数字是2。但是显示的第二个数字是0,这就是我迷路的地方。

例如,我有public Customer CreateCustomer()一个返回 Customer 类的方法,我要写的第一行是AllAccounts = new List<Account>();. 后来我发现它不起作用,然后我决定在构造函数中初始化列表。

public Customer()
        {
            AllAccounts = new List<Account>();
        }

它仍然没有保留我对AllAccounts列表所做的任何更改。

我最近的尝试是在 main 中初始化AllAccounts列表,这在尝试显示长度时给了我一个 null 错误。

我想了解我缺少什么以及我错在哪里。

谢谢阅读。

编辑

这是我的 Customer、构造函数和 CreateCustomer 方法的属性:

客户.cs

        private int pinNumber { get; set; }
        private string accountNumber { get; set; }
        public List<Account> AllAccounts { get; set; }

        public Customer()
        {
            AllAccounts = new List<Account>();
        }

        public Customer CreateCustomer()
        {
            string full = "accountnumber"; // Just a login thing, dont mind
            int pin = 1; // same here
            string path = "Customers";
            string saving = path + "\\saving.txt";
            string current = path + "\\current.txt";
            AllAccounts.Add(new Account() { path = saving, name = "saving", total = 0 });
            AllAccounts.Add(new Account() { path = current, name = "current", total = 0 });
            return new Customer() { firstName = firstName, lastName = lastName, pinNumber = pin, accountNumber = full };
        }

在 program.cs 中,这就是我调用 createcustomer 方法的方式:

var Client = new Customer();
//get client info
AllCustomers.Add(Client.CreateCustomer());

将我的客户添加到* AllCustomers* 后,名字和姓氏会被保存,但不会保存AllAccounts上的内容。

当我运行这个:

Console.WriteLine(AllCustomers[0].AllAccounts[0].name); 

它基本上显示 null,甚至没有显示错误,它只是一个 null 字符。

顺便感谢您的回复!

标签: c#

解决方案


那么问题是当你回来new Customer()的时候CreateCustomer()。您没有传递由CreateCustomer().

return new Customer() { firstName = firstName, lastName = lastName, pinNumber = pin, accountNumber = full,AllAccounts=AllAccounts };

所以,现在你创建了一个新的Account list,但它基本上没有分配给客户,因此没有任何客户的帐户,一旦你创建了一个新的客户,因为new Account List所有先前数据的构造函数初始化都会丢失。

更新您的退货声明,它会起作用


推荐阅读