我有一个类Cars,在该方法中,get_cars()我创建了多个Cars并将它们作为数组返回cars。在我的课堂上Home,我有main()要在数组“ cars”上工作的方法。在示例中,我只想写下每辆汽车的名称。但似乎该name属性为空。我做错什么了?
class Car
{
//only one attribute for test
public string name;
// public string color;
// public string brand;
public car()
{
}
//create multiple Car, limited to 2 for the test und return them in an array
public static Car[] get_cars()
{
Car[] cars = new Car[2];
for (int k = 0; k<cars.Length; k++)
{
cars[k] = new Car();
cars[k].name = "Car 0" + k;
}
return cars;
}
}
class Home
{
private void Main()
{
Car[] cars = new Car[2];
cars = Car.get_cars();
cars[0] = new Car();
//the output is empty, it seems that cars[0].name is emtpy;
set_label_header(cars[0].name);
cars[1] = new Car();
//the output is empty, it seems that cars[1].name is emtpy;
set_label_header(cars[1].name);
//that works
set_label_header("test");
}
}
Run Code Online (Sandbox Code Playgroud)
但似乎“名称”属性为空
这是因为以下行:
cars[0] = new Car();
Run Code Online (Sandbox Code Playgroud)
new Car()会使用干净的状态创建一个新对象,并且您只需设置其ID,因此name为空。通过该get_cars方法,您已经返回了实例化的对象,因此您无需再次实例化。
您实际上不需要更新它。
以下代码对您的情况足够公平:
Car[] cars = Car.get_cars();
Run Code Online (Sandbox Code Playgroud)
然后调用您的方法:
set_label_header(cars[0].name);
Run Code Online (Sandbox Code Playgroud)