這是我的類,名爲「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();
後I輸入 「溫度」 的值,我它存儲到列表:
List<Objek> Objek = new List<Objek>();
與Objek.Add(temp);
問題是每當我改變元素的屬性值(例如:Objek[0].Warna = Color.Red
)中的一個存儲多於1「TEMP」對象之後,所有Objek[0, 1, ..., n].Warna
也改變爲紅色。
有人可以解釋我在這些代碼中哪裏是我的錯?
你存儲在你的列表中Objek'的'同一實例的多個引用,沒有創造Objeck'的'多個實例,他們每個人存儲在列表中。 –
你可以在這裏添加'form1.cs'的相關代碼嗎?特別是當你增加價值的部分,因爲現在我們只能推測你的問題的原因。它看起來很可能是你添加相同的對象,而不是一個不同的... – Fabjan