对象[,]在c#中意味着什么?

Mic*_*ael 7 c# arrays excel vsto matrix

所以我从旧的VSTO项目中看到了我的一些代码,并注意到这一点:

Excel.Worksheet sheet = Globals.ThisAddIn.Application.Worksheets["Unique Hits Per URL"];
        Dictionary<int, string> ids = new Dictionary<int, string>();
        object[,] cellRange = (object[,])sheet.get_Range("E:E").Cells.Value;
        for (int i = 1; i < cellRange.GetUpperBound(0); i++)
            if (cellRange[i, 1] != null)
                ids.Add(i, cellRange[i, 1].ToString());
Run Code Online (Sandbox Code Playgroud)

在数据类型上指定[,]意味着什么?看看代码它看起来像一个矩阵,但老实说我认为c#矩阵是用object [] []这样的符号来处理的.

Aid*_*api 16

object[,]指的是一个矩形数组,这意味着它是一个网格.
然后你有object[][]一个锯齿状数组,一个数组数组.

主要区别在于object[,]始终具有固定尺寸,而使用锯齿状数组(object[][])时,所有数组都可以具有不同的尺寸.

这是一个清楚地显示使用差异的示例(两者都相同):

// Create and fill the rectangluar array
int[,] rectangularArray = new int[10, 20];
for (int i = 0; i < 200; i++)
    rectangularArray[i / 20, i % 20] = i;

// Next line is an error:
// int[][] jaggedArray = new int[10][20];
int[][] jaggedArray = new int[10][]; // Initialize it

// Fill the jagged array
for (int i = 0; i < 200; i++)
{
    if (i % 20 == 0)
        jaggedArray[i / 20] = new int[20]; // This size doesn't have to be fixed
    jaggedArray[i / 20][i % 20] = i;
}

// Print all items in the rectangular array
foreach (int i in rectangularArray)
    Console.WriteLine(i);

// Print all items in the jagged array
// foreach (int i in jaggedArray) <-- Error
foreach (int[] innerArray in jaggedArray)
    foreach (int i in innerArray)
        Console.WriteLine(i);
Run Code Online (Sandbox Code Playgroud)

编辑:
警告,上面的代码不是真正的生产代码,它只是最简单的方式作为例子.
通过密集使用分裂/%使其慢得多.你可以更好地使用嵌套的for循环.

  • +1对比[,]和[] []非常好,简洁. (3认同)