对象列表错误更新

编程入门 行业动态 更新时间:2024-10-12 08:24:01
本文介绍了对象列表错误更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是班上

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.

更多推荐

对象列表错误更新

本文发布于:2023-07-09 21:20:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1088243.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   错误   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!