2015-05-09 99 views
0

我有一個基地「車輛」類:C#ArrayList.Add通過Ref添加?

public abstract class Vehicle 
{ 
    private string company; 
    private string model; 

    private static int ID = 0; 

    public Vehicle(string company, string model) 
    { 
     this.company = company; 
     this.model = model; 
     ID++; 
    } 

    public override string ToString() 
    { 
      return "\n\nVehicle Information: \n\t" + 
        "ID: "+ID+"\n\t"+ 
        "Car: " + company + "\n\t" + 
        "Model: " + model + "\n\t"; 
    } 
} 

現在我已經繼承的類「福特」,從整車繼承:

public class Ford : Vehicle 
{ 
    public Ford(string company, string model) : 
           base(company, model) 
    { 

    }   
} 

我也有另一種繼承的類「本田」,承襲從車輛:

public class Honda: Vehicle 
{ 
    public Honda(string company, string model) : 
           base(company, model) 
    { 

    }   
} 

現在,在我的主要方法,我稱之爲派生類福特和本田,並將它們添加到一個ArrayList:

class Test 
{ 
    static void Main(string[] args) 
    { 
     ArrayList vehicleList = new ArrayList(); 

     Ford firstVehicle = new Ford("Ford", "Fusion"); 
     vehicleList.Add(firstVehicle); 


     vehicleList.Add(new Honda("Honda", "Civic")); 


     foreach (Vehicle x in vehicleList) 
     { 
      Console.WriteLine(x); 
     } 
    } 
} 

的問題是,當我運行它,我得到以下的輸出:

Vehicle Information: 
    ID:2 
    Car:Ford 
    Model:Fusion 
Vehicle Information: 
    ID:2 
    Car:Honda 
    Model:Civic 

正如你所看到的,對象顯示ID列「2」,而不是1對第一第二個爲2。 當我使用斷點來檢測發生了什麼事情時,我看到當處理第一個對象時,arrayList爲第一個對象顯示ID = 1,但是當第二個對象被處理並添加到arrayList時,第一個對象也從1改爲2. 我認爲這是因爲它使用'add by reference'? 有什麼建議我能做些什麼來顯示ID:第一個是ID,第二個是ID:2?

回答

0
private static int ID = 0; 
private int instanceID; 
public Vehicle(string company, string model) 
{ 
    this.company = company; 
    this.model = model; 
    instanceID = ID++; 
} 

...並使用ToString()instanceID

1

ID是靜態的,因此是一個單身人士。目前是應用它的一個實例(由車輛的所有實例共享)

開始通過改變這樣的:

private static int ID = 0; 

要這樣:

private static intCounter = 0; 
private int ID = 0; 

然後你自己的ID被設置更換:

ID++; 

...與...

intCounter++; 
ID = intCounter; 
+0

那麼我的選擇是什麼? –

+1

@RajivGanti,不要使用靜態'ID' ...爲什麼你需要一個靜態ID在這種情況下?謹慎解釋? – davidshen84

+0

我已經添加了一個適合你的解決方案。 – garryp