【问题标题】:Having trouble initialising an array of a custom class初始化自定义类的数组时遇到问题
【发布时间】:2017-06-21 19:45:14
【问题描述】:

代码如下:

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'

我不是要索引它,而是要初始化一个数组 of 它,使用与Microsoft's own tutorial 完全相同的语法。

谁能发现什么是明显的错误?

【问题讨论】:

    标签: c# arrays unity3d


    【解决方案1】:

    3d 数组有区别,可以一次性初始化:

      Rhomb[,,] map = new Rhomb[sizeX, sizeY, sizeZ];
    

    jagged 数组(数组的数组),您必须在其中创建每个内部数组:

      Rhomb[][][] map = Enumerable
        .Range(0, SizeX)
        .Select(x => Enumerable
           .Range(0, SizeY)
           .Select(y => new Rhomb[SizeZ])
           .ToArray())
        .ToArray(); 
    

    请注意,您在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], 
    }; 
    

    【讨论】:

    • 啊,所以我需要依次初始化每个子数组?你看,我需要使用锯齿状数组,因为它们的长度并不相同。
    • @Tim 不,这不是锯齿状的意思。锯齿状意味着行之间的元素数量变化。如果您试图表示一个立方体形状的形状,那么 3d 数组是更好的。
    • @Scott 抱歉,我不是很清楚我在说什么,数组确实都是不同的长度,这就是为什么我需要使用锯齿状的。不过感谢您的澄清!
    • @TimLeach 我真的认为你不明白我在说什么。从您的示例代码中,您的所有行在每个轴上的长度都相同。那是当您使用 3d 数组时。 map = new Romb[sizeX, sizeY, sizeZ];
    • @Scott 我明白,稍后我将更改代码,以便一切都是可变的,我只是尝试从最简单的情况开始。当我为这个地图对象实现不同的“形状”时,我需要有不同的尺寸,因为我正在做类似this,但在 3D 中。
    【解决方案2】:
    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[,,] 的解决方案是最好的。

    【讨论】:

    • 谢谢!问题是,这仍然返回完全相同的错误:(
    • @TimLeach 很抱歉,我什至没有抓住 Dmitry 的回答所涉及的锯齿状阵列/3D 阵列。我已经编辑了我的答案
    猜你喜欢
    • 2020-11-22
    • 2011-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2020-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多