gpt4 book ai didi

c# - 声明二维数组的问题

转载 作者:行者123 更新时间:2023-11-30 13:38:37 25 4
gpt4 key购买 nike

我有以下代码:

    public int[] _SpDep = new int[50];
public int[][] _SpDepCnt = new int[50][];
public int[][] _SpReadType = new int[50][];

_DepNo = Convert.ToInt16(strFileName[n].Substring(1, 2));
_CntNo = Convert.ToInt16(strFileName[n].Substring(6, 2));
_SpDep[_DepNo] = 1;
_SpDepCnt[_DepNo][_CntNo] = 1;
_SpReadType[_DepNo][_CntNo] = 1;

到达这一行时出错:

      _SpDepCnt[_DepNo][_CntNo] = 1;

但是不知道怎么回事?有什么意见吗?是不是二维数组声明错误?

最佳答案

交错数组[][]

如果使用类型为 int[][] 的数组(jagged array),您希望像这样初始化您的数组:

public int[] _SpDep = new int[50];
public int[][] _SpDepCnt = new int[50][];
public int[][] _SpReadType = new int[50][];

然后初始化数组中的数组:

var length = 20;
for (int i = 0; i < length; i++)
{
_SpDepCnt[i] = new int[length];
_SpReadType[i] = new int[length];
}

它被称为锯齿状数组,因为第二部分的长度可以变化,例如:

[1,2,3,4]
[5,6]
[7,8,9]

多维数组[,]

我相信你想使用 int[,] 类型,它被称为 multidimensional array .他们制作了一个具有两个固定维度的数组。

public int[,] _SpDepCnt = new int[50, 20];
public int[][] _SpReadType = new int[50, 20];

多维数组将为每个索引创建相同大小的数组:

[1,2,3]
[4,5,6]
[7,8,9]

关于c# - 声明二维数组的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15782013/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com