更新时间:2023-01-16 22:08:43
试试这个:
Try this :
Car[] cars =new Car[2]; // you cannot use Array since it is a reserved CLR object
cars[0] = new Car();
cars[1] = new Car();
嗯,你的语法有点'out'那里....如果你的对象'Car'有一个构造函数,它带有制造商,颜色和注释(例如,全部作为字符串) ,你可以这样做
Well, your syntax is a bit 'out' there .... if your object 'Car' has a constructor that takes the Manufacturer, Color and Comment (for example, all as strings), you could do this
Car[] CarsCollection = new Car[]
{
new Car("Holden", "Blue", "Goes Slow"),
new Car("FIAT", "Red", "Goes Faster")
};
例如
注意:如果您有一系列汽车,那么您就不能再添加火车了!
for example
NB : if you have an array of Cars, you cant then add a Train to it !
如果您需要,可以使用 ArrayList类(System.Collections) [ ^ ]存储任何对象。
Ex ample
If you want you can use the ArrayList Class (System.Collections)[^] to store any object.
Example
ArrayList arr = new ArrayList();
arr.Add(new Car()); // First car at index 0
arr.Add(new Car()); // Second car at index 1
(不建议将此课程用于新项目)
更好的方法是使用列表 [ ^ ]如果对象属于同一类型:
(It is not recommended to use this class for new projects)
A better way is to use a List[^] if the objects are of the same type:
List<car> list = new List<car>();
list.Add(new Car());
list.Add(new Car());</car></car>
其他方式已经在其他解决方案中提到了。
要了解C#中的数组,你可以从这里开始:
Arrays(C#编程指南) [ ^ ]