本文介绍了更改对象列表中的一个元素属性值也会更改所有元素值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的班级,名称为"Objek".

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>();
    }
}

然后在form1.cs中,我在所有方法之外全局声明了这一点:

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

Objek temp = new Objek();

输入"temp"的值后,将其存储到列表中:

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

List<Objek> Objek = new List<Objek>();Objek.Add(temp);问题是,每当我存储了多个临时"对象后,只要更改元素的一个属性值(例如:Objek[0].Warna = Color.Red),所有的Objek[0, 1, ..., n].Warna也会更改为红色.

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?

推荐答案

听起来像是将相同的对象引用添加到列表中.将Objek temp = new Objek();移到方法内部,以便每次创建一个新对象,否则,每次调用此方法时,它都会使用/添加同一对象.

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.

这篇关于更改对象列表中的一个元素属性值也会更改所有元素值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 21:15