Model view controller MVC#:在不同的模型中使用相同的对象列表(参考?)
我想在不同的模型中使用相同的对象列表。MainModel应该关注列表的内容,这样使用该列表的子模型也会得到更改 给定以下模型“客户”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
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);
}