如何创建通用类作为数组 [英] how to create generic class as array

查看:64
本文介绍了如何创建通用类作为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们该怎么做.

像这样的常规数组.

How can we do like this.

general arrays like this below.

class []emp  = new emp[3];


但是如何使用泛型


but how to do using Generics

List<emp>[]emp = new List<emp>[3];


使用集合初始化,我知道:


using collection initialisation I know:

like List<class>obj = new List<obj>{
new class{},
new class{},
new class{}
};


指导我,这是否可能.


guide me,is this possible or not.

推荐答案

您没有提供大小,只是执行新的List< emp>(),因为它可以做到这一点"如果您向其中添加项目是一个空集合,它可以更改大小.数组不能,所以您必须告诉它多大.

您可以使用{1,2,3}创建一个数组,因此我想如果Array类具有ToList(并且我认为确实有),那么您可以按照想像的方式使用它,尽管它很容易在创建三个对象后将其推入.
You don''t give a size, you just do new List<emp>(), because it''s an empty collection you add items to, it can change size. An array cannot, so you have to tell it how big it is.

You can create an array with { 1,2,3 }, so I imagine if the Array class has a ToList ( and I think it does ), then you could use it in the manner you imagine, although it''s as easy to push the three objects in after creating it.


1.)整数的通用列表:
1.) Generic List of Integers:
List<int> intList = new List<int>();

intList.Add(1);
intList.Add(2);
intList.Add(3);


//int[] fixedSizeArray = intList.ToArray();



2.)整数数组列表:



2.) List of Integer-Arrays:

List<int[]> intArrayList = new List<int[]>();

intArrayList.Add(new int[]{1, 2, 3});
intArrayList.Add(new int[]{4, 5, 6});
intArrayList.Add(new int[]{7, 8, 9});


//int[][] intArrayArray = intArrayList.ToArray();



3.)整数列表数组:



3.) Array of List of Integers:

List<int>[] listArray = new List<int>() {
  new List<int>(),
  new List<int>(),
  new List<int>()
}

listArray[0].Add(1);
listArray[0].Add(2);
listArray[0].Add(3);
listArray[1].Add(4);
listArray[1].Add(5);
listArray[1].Add(6);



为了清楚起见,我没有使用var-keyword.
多数民众赞成在情况3)中构建各种结构的方式是可行的,但感觉并不正确.但是,这完全取决于您要实现的目标.
记住要初始化List< t>的实例.算一下,如果您知道要执行多少次Add调用(即List实例将容纳多少个元素),那么Runtime可以为这些元素保留足够的空间.否则,运行时将每四个(或大约四个)元素扩大列表,这将导致性能下降(请参考 MSDN [ ^ ]了解更多详情)



For clarity, i did not use the var-keyword.
Thats how you would build up the various constructs, case 3.) is possible, but doesnt feel right. However, it all depends on what you are trying to achieve.
Remember to initialize instances of List<t> with a count, if you know how many calls to Add you are going to do (that is, how much elements the List-instance will hold), so the Runtime can reserve enough space for the elements. Otherwise the runtime will enlarge the List every 4 (or so)Elements, which will result in poor performance (refer MSDN [^]for mor details)


这篇关于如何创建通用类作为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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