简体   繁体   English

C# 更新列表中的对象

[英]C# updating an object within a list

I have this object list named list<product> A within class USER , there is also a list<USER> in the main program we name list C.我在类USER中有list<product> A名为list<product> A对象列表,在我们命名列表 C 的主程序中还有一个list<USER>

List A will be updated every time the user buya something from another list<product> B (this on is on the main class) that contains every product we have and some additional information on how much it costs (based on user age) and when it was bought (which variable exist from the product class, although it's empty when it's inside list A as I only want to save the product name, and product description in list B).每次用户从另一个list<product> B (这是在主类上)购买东西时,List A 将更新,其中包含我们拥有的每个产品以及有关其成本(基于用户年龄)和时间的一些附加信息它被购买了(产品类中存在哪个变量,尽管它在列表 A 中时它是空的,因为我只想在列表 B 中保存产品名称和产品描述)。

If the product the user bought does not exist in list B then it will print "no product exists".如果用户购买的产品不存在于列表 B 中,那么它将打印“不存在产品”。 If it exist it will add the product the user bought to List A. The program does not run as intended, the add to list A is running fine (although it somehow updates the list B product with the same name?), if the user buys a different product but if it's the same product the list A will update every list in list product???如果它存在,它会将用户购买的产品添加到列表 A。程序没有按预期运行,添加到列表 A 运行正常(尽管它以某种方式更新了具有相同名称的列表 B 产品?),如果用户购买不同的产品但如果它是相同的产品列表 A 将更新列表产品中的每个列表???

Here is the add product code:这是添加产品代码:

public static Produk Sehat = new Produk("Sehat Bersama",EnumJenisKesehatan.Kesehatan
        ,EnumFrequensi.Bulanan,"Claim Perawatan kelas 1");

public static Produk SehatExtr = new Produk("Sehat Extra", EnumJenisKesehatan.Kesehatan
        , EnumFrequensi.Bulanan, "Claim Perawatan VIP"); 

public static List<Produk> allprod = new List<Produk>()
        { Sehat,SehatExtr};

Here is the add product to list (with the assumption that we've got the product we want to add, and the user that bought it).这是将产品添加到列表(假设我们已经获得了想要添加的产品以及购买它的用户)。

Tempuser._produk.Add(produk);

Here is the one that adds the price in user class to the product list (again with the asumption that we've already got the product from the user list[product]).这是将用户类中的价格添加到产品列表的方法(再次假设我们已经从用户列表[产品] 中获得了产品)。

int price;

if (User._age < 20)
{
    price= 200000m;
    product._price= price;
}
else
{    
    price=300000m;  
    product._price=price; 
}

I even made the product list into a dictionary (with product as value and and ID as the key) but the code still updates every product with the same name and my senior tends to get mad at me, if I ask her this kind of question....我什至将产品列表制作成字典(以产品为值,以 ID 为键),但代码仍会更新同名的每个产品,如果我问她这种问题,我的前辈往往会生我的气....

Please someone is there some kind of solution to this?请问有人有什么解决办法吗?

You are likely sharing the same object (reference) between 2 lists, so the price / name / or anything else will be reflected in both lists (as it's the same object).您可能在 2 个列表之间共享相同的对象(引用),因此价格/名称/或其他任何内容都将反映在两个列表中(因为它是同一个对象)。

You can think of a reference as a piece of paper which has the address of a physical location of stuff .你能想到的引用作为一张纸,它具有的东西,一个物理位置的地址。 When you are adding the reference to a list, or copy it.当您将引用添加到列表时,或复制它。 You are just coping the that piece of paper (the address).你只是在处理那张纸(地址)。 When you change a property, it looks up the actual physical location and it changes the stuff for everyone.当您更改属性时,它会查找实际的物理位置并为每个人更改内容。

What you will need to do is clone your product.您需要做的是克隆您的产品。 There are lots of ways to do this, some easier than others.有很多方法可以做到这一点,有些方法比其他方法更容易。 However the most fundamental way is just copy the properties and state.然而,最基本的方法只是复制属性和状态。 Such that the internal state is the same.这样内部状态是相同的。

var newProduk = new Produk() 
                     {
                         Price = produk.Price,
                         Name = produk.Name,
                         ...
                         // the rest of your state and properties
                     };

Tempuser._produk.Add(newProduk );

When you assign a product of list B to list A, you're assigning a reference to the product, not a copy of it, so when you change it in list A you're actually changing the same product in list B, too.当您将列表 B 的产品分配到列表 A 时,您分配的是对该产品的引用,而不是它的副本,因此当您在列表 A 中更改它时,实际上也更改了列表 B 中的相同产品。

If copying is what you need then clone the object in B to list A. Here's an example of how to clone an object:如果您需要复制,则将 B 中的对象克隆到列表 A。以下是如何克隆对象的示例:

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var listA = new List<MyObj>();
        var listB = new List<MyObj>();

        listB.Add(new MyObj{Name="John", Surname="Smith"});
        listA.Add((MyObj)listB[0].Clone());

        listA[0].Name = "Michael"; 

        Console.WriteLine(listA[0].Name);
        Console.WriteLine(listB[0].Name); 
    }
}

class MyObj: ICloneable
{
    public string Name {get;set;}
    public string Surname {get;set;}

    public object Clone() 
    {
        return (MyObj)this.MemberwiseClone();
    }
}

You can run this sample in https://dotnetfiddle.net to see it in action.您可以在https://dotnetfiddle.net 中运行此示例以查看其实际效果。

Hope this helps :)希望这可以帮助 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM