C#ArrayList.Add由Ref?

时间:2015-05-09 23:06:05

标签: c# inheritance arraylist

我有一个基础'车辆'类:

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";
    }
}

现在我有一个继承的类'Ford',继承自Vehicle:

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

    }        
}

我还有另一个继承的类'Honda',继承自Vehicle:

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

    }        
}

现在在我的Main方法中,我调用派生类Ford和Honda,并将它们添加到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时,第一个对象的ID值对象也从1改为2。 我认为这是因为它使用'按引用添加'? 有什么建议我可以做什么来显示ID:1表示第一个ID:2表示第二个?

2 个答案:

答案 0 :(得分:1)

ID是静态的,因此是单例。应用程序有一个实例(由Vehicle的所有实例共享)

首先改变这个:

private static int ID = 0;

对此:

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

然后在您的ID设置位置替换:

ID++;

...与...

intCounter++;
ID = intCounter;

答案 1 :(得分:0)

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

...并在instanceID中使用ToString()