【发布时间】:2019-07-23 20:03:33
【问题描述】:
我创建了一个静态类,其中包含了全局变量和函数的定义,但可能是错误的。
我需要创建一个购物车,刷新后内容不应该丢失。
在静态类 A 中,我创建了静态变量 ObservableCollection Collection1 和 Collection2(Collection1 有子但 Collection2)和静态函数 Refresh() 用于刷新 Collection1。
在动态类B中,获取一些children,添加到Collection2中,然后使用A.Refresh(),在刷新的过程中,如果新数据的id与旧Collection2中的任何一个id相同,则将其添加到new中收藏2。
public class Model
{
public Guid Id{ get; set; }
public string Name{ get; set; }
}
public static class A
{
public static ObservableCollection<Model> Collection1 { get; set; } = new ObservableCollection<Model>();
public static ObservableCollection<Model> Collection2 { get; set; } = new ObservableCollection<Model>();
public static Refresh()
{
var uidList = Collection2.Select(x => x.Id).ToList();
Collection1.Clear();
Collection2.Clear();
foreach (var item in dataFromServer)
{
var newModel = new Model{Id = item.Id};
Collection1.Add(newModel);
if(uidList.Contains(item.Id))
{
Collection2.Add(newModel);
}
}
}
}
public class B
{
public B()
{
A.Refresh();
}
public AddToCart(Guid id)
{
var model = A.Collection1.First(x=>x.Id == id);
if (!A.Collection2.Contains(model))
{
A.Collection2.Add(model);
}
}
public Refresh()
{
A.Refresh();
}
}
我使用 B.AddToCart(AAAA) 将子项添加到 Collection2,然后使用 B.Refresh(),现在我有新的数据表单服务器,Collection1 和 Collection2 中有一个新对象(Id 为 AAAA)。然后我使用B.AddToCart(AAAA) 再次,现在 Collection2 有两个具有相同 Id 和 Name 的孩子,即使我改变了一个,另一个的名字也改变了。这意味着 Collection2 中有相同的两个对象对吗?但是为什么 A.Collection2 .Contains(model) return false?我用 Object.ReferenceEquals 检查了两个孩子,结果也是 false。 我知道 Collection2.Any(x=>x.Id==id) 可以工作,我只是想知道它是怎么发生的。
编辑:我创建了一个演示,但他的问题没有再次出现,可能是其他部分有问题。
【问题讨论】: