[英]How to declare this nested array/list?
我有一个自定义类Gene
我想声明一个名为_slots
的数组或列表(或其他更好的东西), _slots
具有400个位置...类似_slots[400]
。
每个_slot
必须包含一个解决方案。 但是,一个解决方案是我的自定义类Gene
的数组100。类似这样的:
_Slots
-------------
0 | Gene[100] |
--------------
1 | Gene[100] |
--------------
2 | Gene[100] |
--------------
3 | Gene[100] |
--------------
4 | Gene[100] |
--------------
...
400 | Gene[100] |
--------------
声明此内容并轻松访问所有成员的最佳方法是什么?
更好的方法是有一个代表一类Slot
,这反过来又管理着100个实例Gene
。
然后,使用400个插槽的数组(或IEnumerable
或List<Slot>
,以满足您的需要)。
public class Slot
{
private Gene[] _genes;
public Gene this[int index]
{
get{ return _genes[index];}
set{ _genes[index] = value;}
}
public Slot(int count = 100)
{
_genes = new Gene[count];
}
}
IList<Slot> slotsList = Enumerable.Range(0,400)
.Select(i => new Slot())
.ToList();
//or an enumerable
IEnumerable<Slot> slots = slotsList;
//or an array
Slot[] slotsArray = slotsList.ToArray();
尝试使用
List<Gene[]> MegaList = new List<Gene[]>();
MegaList.Add(new Gene[100]);
MegaList[0][0] = new Gene();
我强烈建议将此功能包装到类中,以便将来方便地扩展它,例如:
public class MultiArray<T> : List<T> { }
...
MultiArray<Gene[]> Storage = new MultiArray<Gene[]>();
由于每个维度的长度相同,因此二维数组似乎很合理。
Gene[,]
另外,如果数组的数目是可变的,而不是设置值400,则可以使用List<Gene[]>
List<Gene>[] lst = new List<Gene>[400];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.