我们可以在C#中使用具有自定义数据类型的数组吗? [英] Can we use arrays with custom datatypes in C#?

查看:81
本文介绍了我们可以在C#中使用具有自定义数据类型的数组吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我通过Arrays主题时,我是一个C#初学者,我有一个疑问,即我们可以使用自定义类型的数组。



我是什么尝试过:



我声明了一个自定义类型的数组,但我不知道如何使用对象初始化该数组。

Car [] Array = new car [2];

I am a C# beginner when i was going through Arrays topic , i got a doubt i.e can we use arrays with custom types.

What I have tried:

I declared a array with custom type but i don't know how to initialize that array with objects.
Car[] Array =new car[2];

推荐答案

试试这个:

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#编程指南) [ ^ ]


这篇关于我们可以在C#中使用具有自定义数据类型的数组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆