我目前正在学习如何创建类和使用索引器。我创建了两个类list_of_cars
和the_cars
. 使用button1
I 可以在列表中显示汽车,但不是显示三辆汽车,而是只显示两辆。我不知道为什么它错过了最后一辆车?
代码
namespace cars
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public class list_of_cars
{
public the_cars first;
public the_cars last;
public int count;
public list_of_cars(the_cars new_car)
{
first = new_car;
last = new_car;
count = 1;
}
public void add_car(the_cars new_car)
{
if (count == 0)
{
first = new_car;
last = new_car;
count = 1;
}
else
{
last.next = new_car;
last = new_car;
count++;
}
}
}
public class the_cars
{
private string name;
private int year;
private double price;
public the_cars next;
public the_cars(string new_name, int new_year, double new_price)
{
name = new_name;
year = new_year;
price = new_price;
next = null;
}
public override string ToString()
{
return name + " " + year.ToString() + " " + price.ToString();
}
}
private void button2_Click(object sender, EventArgs e)
{
the_cars car0 = new the_cars("VW Bug", 1960, 600.0);
the_cars car1 = new the_cars("Ford Pinto", 1970, 2400.0);
the_cars car2 = new the_cars("Duster", 1974, 3200.0);
list_of_cars mylist = new list_of_cars(car0);
mylist.add_car(car1);
mylist.add_car(car2);
the_cars current = mylist.first;
while (current.next != null)
{
textBox1.AppendText(current.ToString() + Environment.NewLine);
current = current.next;
}
}
}
}