c# - 访问方法的返回参数类型数组
问题描述
我有一个类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");
}
}
解决方案
但似乎“名称”属性为空
这是因为以下行:
cars[0] = new Car();
new Car()
创建一个干净的新对象,你只设置它的 id,所以它name
是空的。从get_cars
您已经返回实例化对象的方法中,您不需要再次实例化。
你实际上不需要更新它。
对于您的情况,以下代码足够公平:
Car[] cars = Car.get_cars();
然后调用你的方法:
set_label_header(cars[0].name);
推荐阅读
- ios - 在 iOS 中从套接字读取/写入时崩溃
- angular - Ngrx 选择器组成循环依赖
- c++ - C++:高分辨率屏幕缺少方法 GetSystemMetricsForDpi()
- android-room - 当 OnConflict = OnConflictStrategy.IGNORE 时检测到房间数据库中的插入失败
- php - Laravel Eloquent - 如何使用父模型仅获取每个父模型的 2 个子模型?
- javascript - 下拉菜单 - 一次只打开一个菜单
- android - 如何使用 iOS 和 android 的 react native 显示覆盖页面?
- java - 如何使用 Jsoup 从每个 div 中获取第一个 href 标签
- netlogo - 被要求去某些地区的海龟都聚集在一个地方
- c++ - 按值分配与按引用分配?