我目前正在学习如何创建类和使用索引器。我创建了两个类list_of_cars
和the_cars
。使用button1
我可以在列表中显示汽车,但不显示三辆汽车,而只显示两辆汽车。我不知道为什么它错过了最后一辆车?
代码
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;
}
}
}
}
答案 0 :(得分:3)
你的while循环应该是
while(current != null)
答案 1 :(得分:0)
我想这会有所帮助:
list_of_cars mylist = new list_of_cars();
mylist.add_car(car0);
mylist.add_car(car1);
mylist.add_car(car2);