Model view controller MVC#:在不同的模型中使用相同的对象列表(参考?)

Model view controller MVC#:在不同的模型中使用相同的对象列表(参考?),model-view-controller,list,pointers,reference,model,Model View Controller,List,Pointers,Reference,Model,我想在不同的模型中使用相同的对象列表。MainModel应该关注列表的内容,这样使用该列表的子模型也会得到更改 给定以下模型“客户” public class Customer { public Customer(List<Customer> customerList) { this.CustomerList= customerList; this.CustomerAge= new CustomerAge(this.CustomerLi

我想在不同的模型中使用相同的对象列表。MainModel应该关注列表的内容,这样使用该列表的子模型也会得到更改

给定以下模型“客户”

public class Customer
{
    public Customer(List<Customer> customerList)
    {
        this.CustomerList= customerList;
        this.CustomerAge= new CustomerAge(this.CustomerList);
    }

    public List<Customer> CustomerList
    {
        get;
        set;
    }

    public AgeCustomer AgeCustomer
    {
        get;
        set;
    }

    public void SetCustomerList(List<Customer> customerList)
    {
        this.CustomerList= customerList;
    }
}

到目前为止非常简单,我有一个名为
Customer
的主模型和一个名为
CustomerAge
的助手模型。当我通过调用
Customer.SetCustomerList(newCustomerList)
Customer
中更改
CustomerList
时,我认为
CustomerAge
中的
CustomerListComplete
也会更改,但实际上没有。为什么?如何在这两个模型中使用相同的列表?

这是因为您的集合被引用

Customer
中的
CustomerList
CustomerAge
中的
customerListComplete
只是指向集合的“指针”。当您更改
CustomerList
时,
customerListComplete
不会更改

您需要将
public void SetCustomerList(List customerList)
添加到
CustomerAge
并从
Customer.SetCustomerList
调用它

另一种解决方案是更改
CustomerAge
构造函数以获取
Customer
的实例,然后使用
Customer.CustomerList

public Customer(List<Customer> customerList)
{
    this.CustomerList= customerList;
    this.CustomerAge= new CustomerAge(this);
}
公共客户(列表客户列表)
{
this.CustomerList=CustomerList;
this.CustomerAge=新CustomerAge(this);
}

谢谢,我采用了第二种解决方案。我认为,还有一个解决方案是更改
SetCustomerList()
this.CustomerList.Clear()
,然后再更改
this.CustomerList.AddRange(CustomerList)
,所以我不更改引用,而是更改引用的内容。我说得对吗?
public Customer(List<Customer> customerList)
{
    this.CustomerList= customerList;
    this.CustomerAge= new CustomerAge(this);
}