[英]Having trouble initialising an array of a custom class
这是代码:
public class RhombMap
{
private Vector3 size;
private Rhomb[][][] map;
public RhombMap( int sizeX, int sizeY, int sizeZ )
{
size = new Vector3 (sizeX, sizeY, sizeZ);
Rhomb[][][] map = new Rhomb[sizeX] [sizeY] [sizeZ];
}
}
这令人讨厌地给我错误:
Assets/Scripts/MapController.cs(186,46): error CS0021: Cannot apply indexing
with [] to an expression of type `Rhomb'
我并不想建立索引呢,我试着初始化它的一个阵列,使用完全相同的语法在微软自己的教程 。
谁能发现一个明显的错误?
您可以一口气初始化3d数组之间的区别:
Rhomb[,,] map = new Rhomb[sizeX, sizeY, sizeZ];
和锯齿状数组(array of array of array),您必须在其中创建每个内部数组:
Rhomb[][][] map = Enumerable
.Range(0, SizeX)
.Select(x => Enumerable
.Range(0, SizeY)
.Select(y => new Rhomb[SizeZ])
.ToArray())
.ToArray();
请注意,您已在RhombMap
构造函数RhombMap
map
重新声明为局部变量
编辑: 2d数组(让我不要放3d )和锯齿状的插图之间的区别:
// 2d: always rectangle (2x3 in this case - 2 rows each of 3 items)
// that's why when been initializing wants just width and height
int[,] arr2d = new int[,]
{{1, 2, 3}
{4, 5, 6}};
// width and hight
int[,] arr2d_empty = new int[2, 3];
// jagged: all rows (subarrays) are of arbitrary lengths
// that's why when been initializing wants all rows been initialized individually
int[][] jagged = new int[][] {
new int[] {1, 2, 3, 4}, // 4 items
new int[] {5}, // 1 item
new int[] {6, 7, 8}, // 3 items
};
// each line (subarray) must be specified
int[][] jagged_empty = new int[][] {
new int[4],
new int[1],
new int[3],
};
private Rhomb[][][] map;
...
Rhomb[][][] map = ...
您已经声明了一个具有相同名称的新变量。
另外,由于您声明了一个数组数组,因此您无法一行创建一个新实例。 您可以使用Dmitry的解决方案之一,也可以这样进行:
map = new Rhomb[sizeX][][];
for(int x = 0; x < sizeX; x++) {
map[x] = new Rhomb[sizeY][];
for(int y = 0; y < sizeY; y++) {
map[x][y] = new Rhomb[sizeZ];
}
}
我仍然认为Dmitry的将数组声明为Rhomb[,,]
的解决方案是最好的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.