首页 > 解决方案 > 访问方法的返回参数类型数组

问题描述

我有一个类Cars,在方法中get_cars()我创建了多个Cars并将它们作为数组返回cars。在我的课堂Home上,我有main()我想使用数组“汽车”的方法。在示例中,我只想写下每辆车的名称。但似乎该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");
    }
}

标签: c#arraysreturn

解决方案


但似乎“名称”属性为空

这是因为以下行:

cars[0] = new Car();

new Car()创建一个干净的新对象,你只设置它的 id,所以它name是空的。从get_cars您已经返回实例化对象的方法中,您不需要再次实例化。

你实际上不需要更新它。

对于您的情况,以下代码足够公平:

Car[] cars = Car.get_cars();

然后调用你的方法:

set_label_header(cars[0].name);

推荐阅读