为什么同时具有锯齿状数组和多维数组? [英] Why we have both jagged array and multidimensional array?
问题描述
-
锯齿状数组和多维数组有什么区别。
彼此有益吗?
What is the difference between jagged array and Multidimensional array. Is there a benefit of one on another?
为什么Visual Studio不允许我做
And why would the Visual Studio not allow me to do a
MyClass[][] abc = new MyClass[10][20];
(我们以前在C ++中这样做,但是在C#中用红色的蠕动线强调[20] ..表示无效的排名说明符)
(We used to do that in C++, but in C# it underlines [20] with red wriggly line.. Says invalid rank specifier)
,但对
MyClass[,] abc = new MyClass[10,20];
最后如何在一行中初始化它(就像我们在简单数组中用 {新xxx ...} {新xxx ....}
)
MyClass[][,][,] itemscollection;
推荐答案
-
锯齿状数组是数组数组,因此
int [] []
是<$ c $数组c> int [] ,每个长度可以不同,并在内存中占据各自的块。多维数组(int [,]
)是一个内存块(本质上是一个矩阵)。
A jagged array is an array-of-arrays, so an
int[][]
is an array ofint[]
, each of which can be of different lengths and occupy their own block in memory. A multidimensional array (int[,]
) is a single block of memory (essentially a matrix).
您不能创建 MyClass [10] [20]
,因为每个子数组都必须分别初始化,因为它们是单独的对象:
You can't create a MyClass[10][20]
because each sub-array has to be initialized separately, as they are separate objects:
MyClass[][] abc = new MyClass[10][];
for (int i=0; i<abc.Length; i++) {
abc[i] = new MyClass[20];
}
A MyClass [10,20]
可以,因为它正在将单个对象初始化为具有10行20列的矩阵。
A MyClass[10,20]
is ok, because it is initializing a single object as a matrix with 10 rows and 20 columns.
A MyClass [] [,] [,]
可以这样初始化(尽管未进行编译测试):
A MyClass[][,][,]
can be initialized like so (not compile tested though):
MyClass[][,][,] abc = new MyClass[10][,][,];
for (int i=0; i<abc.Length; i++) {
abc[i] = new MyClass[20,30][,];
for (int j=0; j<abc[i].GetLength(0); j++) {
for (int k=0; k<abc[i].GetLength(1); k++) {
abc[i][j,k] = new MyClass[40,50];
}
}
}
请记住,CLR已针对单维数组访问进行了优化,因此使用锯齿状数组可能比相同大小的多维数组要快。
Bear in mind, that the CLR is heavily optimized for single-dimension array access, so using a jagged array will likely be faster than a multidimensional array of the same size.
这篇关于为什么同时具有锯齿状数组和多维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!