在C#中初始化多维数组(与其他数组) [英] Initializing multidimensional arrays in c# (with other arrays)
问题描述
在C#中,可以使用如下常量来初始化多维数组:
In C#, it's possible to initialize a multidimensional array using constants like so:
Object[,] twodArray = new Object[,] { {"00", "01", "02"},
{"10", "11", "12"},
{"20", "21", "22"} };
我个人认为,使用硬编码常量初始化数组除了测试练习外对其他任何事情都没有用。无论如何,我迫切需要做的就是使用现有数组初始化一个如上所述的新多维数组。 (它们具有相同的项目计数,但是内容当然仅在运行时定义。)
I personally think initializing an array with hard coded constants is kind of useless for anything other than test exercises. Anyways, what I desperately need to do is initialize a new multidimensional array as above using existing arrays. (Which have the same item count, but contents are of course only defined at runtime).
我想做的一个示例是。
Object[] first = new Object[] {"00", "01", "02"};
Object[] second = new Object[] {"10", "11", "12"};
Object[] third = new Object[] {"20", "21", "22"};
Object[,] twodArray = new Object[,] { first, second, third };
不幸的是,这不能编译为有效代码。很有趣,当我尝试
Unfortunately, this doesn't compile as valid code. Funny enough, when I tried
Object[,] twodArray = new Object[,] { {first}, {second}, {third} };
代码 did 编译并运行,但是结果不是所期望的-3 x 3的对象数组,结果是3 x 1的数组数组,每个数组都有3个元素。发生这种情况时,我将无法使用以下命令访问数组:
The code did compile and run, however the result was not as desired - a 3 by 3 array of Objects, what came out was a 3 by 1 array of arrays, each of which had 3 elements. When that happens, I can't access my array using:
Object val = twodArray[3,3];
我必须去:
Object val = twodArray[3,1][3];
显然不是期望的结果。
那么,有什么方法可以从多个现有数组中初始化这个新的2D数组而无需借助迭代?
So, is there any way to initialize this new 2D array from multiple existing arrays without resorting to iteration?
推荐答案
如果您切换到锯齿状数组,将可以工作:
This would work if you switched to jagged arrays:
int[] arr1 = new[] { 1, 2, 3 };
int[] arr2 = new[] { 4, 5, 6 };
int[] arr3 = new[] { 7, 8, 9 };
int[][] jagged = new[] { arr1, arr2, arr3 };
int six = jagged[1][2];
编辑,以供日后寻找此线索的人
Edit To clarify for people finding this thread in the future
上面的代码示例也不足够,因为它导致数组数组( object [object []] )而不是锯齿数组( object [] [] ),它们在概念上是相同的,但类型却不同。
The code sample above is also inadequate as it results in an array of arrays (object[object[]]) rather than a jagged array (object[][]) which are conceptually the same thing but distinct types.
这篇关于在C#中初始化多维数组(与其他数组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!