使用对象实例化数组 [英] Use of Array of object instantiation

查看:63
本文介绍了使用对象实例化数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要实例化与特定类相关的许多对象.我正在使用数组来处理这种方法-

I need to instantiate a number of objects related to a particular class. I am using an array to handle this approach -

Task[] task = new Task[4];


然后


and then

for (int i = 0; i <= 3; i++)
{
   task[i] = new Task();
}


但是,我不确定这是否是正确的方法,或者是否有一种更有效的方法来处理这些不同的对象.

谢谢


However I am not certain if this is the right approach or if there is a more efficient method to handle these different objects.

Thanks

推荐答案

如果您知道将拥有多少个对象,则数组非常有用,您将找不到更快的东西.

如果您有未知数量的对象,并且需要按顺序访问它们,请使用List< T> (列表内部使用数组).

还有很多其他的集合,但是我必须知道更多一点来说明是否有其他集合比您的案例更适合使用数组或列表.
If you know how many objects you will have, arrays are great and you will not find anything faster.

If you have an unknown number of objects and need to access them ordered, use List<T> (internally a List uses an array).

There are many other collections, but I must know a little more to explain if any other collection is better than an array or a list for your case.


那应该很好.当然,还有很多其他选择,例如:
如果任务的数量总是 一个常数:
That should work fine. Of course there are lot''s of alternatives like:
If the amount of tasks is always a constant:
Task[] task = new Task[4]{ new Task(), new Task(), new Task(), new Task() };


如果声明中的金额可以更改:


If the amount in the declaration can change:

for (int i = 0; i < task.Length; i++)
{
   task[i] = new Task();
}


等等..

至于存储,您可以使用轻量级且快速的数组,但是如果您想要针对集合的更多灵活性和可编程性,则可以考虑使用 ^ ]


and so on..

As for storing you can use array which is lightweight and fast but if you want more flexibility and programmability against the collection then you could consider something from System.Collections.Generic Namespace[^]


这篇关于使用对象实例化数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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