对象列表错误更新 [英] with list of objects updating wrongly

查看:85
本文介绍了对象列表错误更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是班上

 public class CartManage
{
    public int prodId { get; set; }
    // public string prodId { get; set; }
    public int qty { get; set; }
    public string color { get; set; }
    public string size { get; set; }
    public string Name { get; set; }
    public string ShortDescription { get; set; }
    public string Specification { get; set; }
    public double Price { get; set; }

    public string skew { get; set; }
    public string weight { get; set; }
    public string maxqty { get; set; }
    public string productimage { get; set; }
    public string prd_vendor_id { get; set; }
    public string prdDeliveryDays { get; set; }
    public bool GiftingEnabled { get; set; }
    public int GiftingId { get; set; }
}

我用它来管理我网站中的购物车,即列表< CartManage> prodList_temp .现在,当一个人增加购物车中物品的数量时.我在列表中添加了另一个对象(我过去只是增加对象的数量,但是由于某些功能,我必须实现我需要单独的对象).我是通过在列表上执行linq查询并将结果添加到购物车来实现的.

I use this to manage cart in my website i.e List < CartManage > prodList_temp. Now when a person increase the quantity of an item in cart. I add another object in the list(I used to just increase the quantity of the object but due to some functionality i have to implement i need separate objects). I did this by doing a linq query on the list and just adding the result to cart.

var session_updating_data = prodList_temp.Where(p => p.skew == reqired_skew);
prodList_temp.Add(session_updating_data.FirstOrDefault());

我遇到的问题是,当在其中任何一份副本中进行更改时,插入后,更改会反映在所有副本中.例如,我有两个数量的项目A,即购物车包含两个对象,这些对象包含如上所示创建的项目a的详细信息.现在,如果我更改任何一个对象的giftingEnabled属性,它将同时反映在两个对象中.现在,我通过创建一个新对象找到了解决方法.但我想知道为什么会发生这种奇怪的现象,以供将来参考.

The problem im having is that after inserting when ever change anyting in one of the copies the changes are reflected in all the copies. for example i have two quantity of item A, i.e the cart contains two objects containing details of item a created as shown above. Now if I change the giftingEnabled property of any one of the objects it gets reflected in both. Now i found a work around for this by creating a new object. but i would like to know why this weird phenomenon is happening for future reference.

推荐答案

var session_updating_data = prodList_temp.Where(p => p.skew == reqired_skew); prodList_temp.Add(session_updating_data.FirstOrDefault());

var session_updating_data = prodList_temp.Where(p => p.skew == reqired_skew); prodList_temp.Add(session_updating_data.FirstOrDefault());

您正在将对该对象的引用传递到列表中,因此该对象的任何更改都将反映在各处.与创建新对象时一样,它是一个单独的实例.

You are passing a reference to that object to your list, so any change in the object will be reflected everywhere. Where as when you create a new object, it's a separate instance.

这篇关于对象列表错误更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆