Changing one element attribute value in List of ob

2019-03-05 11:49发布

this is my class named "Objek".

public class Objek
{
    public int id;
    public int tipe;
    public int bentuk;
    public List<int> x { get; set; }
    public List<int> y { get; set; }
    public int xC { get; set; }
    public int yC { get; set; }
    public Color Warna { get; set; }
    public Objek()
    {
        this.Warna = Color.Black;
        this.x = new List<int>();
        this.y = new List<int>();
    }
    public Objek(int tipe, int bentuk)
    {
        this.tipe = tipe;
        this.bentuk = bentuk;

        this.Warna = Color.Black;
        this.x = new List<int>();
        this.y = new List<int>();
    }
}

then in the form1.cs I declared this globally (outside any method):

Objek temp = new Objek();

after I input the value of the "temp", I stored it to a List:

List<Objek> Objek = new List<Objek>(); with Objek.Add(temp); the problem is whenever I changed one of the element's attribute value (ex: Objek[0].Warna = Color.Red) after stored more than 1 "temp" object, all Objek[0, 1, ..., n].Warna also changed to Red.

Can someone explain me where is my fault in these code?

标签: c# list oop
3条回答
Melony?
2楼-- · 2019-03-05 12:11

You are inserting the same object more than once so you only have 1 object that is inserted into the list several times therefore changing one changes all. You should be copying the object or creating multiple. This can be done using ICloneable https://msdn.microsoft.com/en-us/library/system.icloneable(v=vs.110).aspx, a library like AutoMapper http://automapper.org/ or just create a new object.

查看更多
欢心
3楼-- · 2019-03-05 12:23

Sounds like you are storing multiple references to the same object.

查看更多
【Aperson】
4楼-- · 2019-03-05 12:27

Sounds like you are adding the same object reference to the List. Move Objek temp = new Objek(); inside the method so that you are creating a new object everytime, otherwise everytime you call this method it is using/adding the same object.

enter image description here

查看更多
登录 后发表回答