这是我的班级,名为“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 中我全局声明了这个(在任何方法之外):
Objek temp = new Objek();
输入“temp”的值后,我将其存储到列表中:
List<Objek> Objek = new List<Objek>();
with Objek.Add(temp);
问题是每当我更改元素的属性值之一(例如:Objek[0].Warna = Color.Red
)存储超过 1 个“temp”对象后,所有Objek[0, 1, ..., n].Warna
也改为红色。
有人可以解释一下这些代码中我的错误在哪里吗?
听起来您正在将相同的对象引用添加到列表中。移动Objek temp = new Objek();
在方法内部,以便您每次都创建一个新对象,否则每次您调用此方法时,它都会使用/添加同一个物体.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)