2015-05-09 43 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