首页 > 解决方案 > 无法获得其中包含数组名称的二维数组的长度

问题描述

我无法获得其中包含其他数组名称的二维数组的长度。喜欢..

int[] a = { 1, 2, 3 };
int[] b = { 23, 4, 6 };
int[][] ab = { a, b };
int r = ab.GetLength(1);

标签: c#arraysmultidimensional-arrayindexoutofboundsexception

解决方案


GetLength(1) 适用于二维数组,您有一个锯齿状数组(数组数组),所有数组只有一个维度。因此,您不能将 1 作为 GetLength 的参数

例如,我会:

int r = ab[1].Length; // the length of the 23,4,6 array

还:

ab.Length //it is 2, there are two 1D arrays in ab

我们称它为锯齿状,因为它不必在每个槽中具有相同长度的数组:

ab[0] = new int[]{1,2,3,4,5};
ab[1] = new int[]{1,2,3,4};

推荐阅读