我正在製作一個Bar對象的ArrayList。然後我希望能夠修改包含在ArrayList中的BarType成員。我創建了一個我的代碼的縮短版本,實際上正在做我想做的事情,但我不明白爲什麼它會這樣做。修改ArrayList中的對象成員
在代碼中,我創建了兩個Bar對象,並將它們填充到一個ArrayList中。我將最後一個條目對象從列表中拖出來,將其轉換爲條。但TMP是BAR對象的新實例,但是當我更改TMP中的值時,它會更改我的數組列表中的值。我不知道它爲什麼這麼做,或者這是更改ArrayList中BarType值的最佳方法。
下面是代碼:
ArrayList barArray = new ArrayList();
Bar myBar = new Bar(10,20);
barArray.Add(myBar); // I want to create and keep adding Bar object to my arraylist
myBar = new Bar(30, 40);
barArray.Add(myBar);
Bar tmp = new Bar(5,6);
tmp = (Bar)barArray[myBar]; // extracting the last Bar Object
tmp.BarType = true;
tmp.High = 100; // too my surprise this change the value in the ArrayList
所以,下面是我的酒吧類:
public class Bar
{
public double High, Low;
public bool BarType; // I want to be able to modify this variable
public Bar(double Low, double High)
{
this.Low = Low; this.High = High;
}
}
任何你需要使用'ArrayList'而不是'List'來折磨的理由? –
2015-03-02 22:33:27