所以事实证明,所有数组都不是平等的。多维数组可以有非零的下界。参见例如 Excel PIA 的 Range.Value 属性object[,] rectData = myRange.Value;
我需要将这些数据转换成锯齿状数组。我第一次尝试下面的复杂性。有什么优化它的建议吗?它需要处理下限可能不为零的一般情况。
我有这个前方法:
public static T[][] AsJagged<T>( this T[,] rect )
{
int row1 = rect.GetLowerBound(0);
int rowN = rect.GetUpperBound(0);
int col1 = rect.GetLowerBound(1);
int colN = rect.GetUpperBound(1);
int height = rowN - row1 + 1;
int width = colN - col1 + 1;
T[][] jagged = new T[height][];
int k = 0;
int l;
for ( int i = row1; i < row1 + height; i++ )
{
l = 0;
T[] temp = new T[width];
for ( int j = col1; j < col1 + width; j++ )
temp[l++] = rect[i, j];
jagged[k++] = temp;
}
return jagged;
}
像这样使用:
public void Foo()
{
int[,] iRect1 = { { 1, 1, 1, 1 }, { 1, 1, 1, 1 }, { 1, 1, 1, 1 }, { 1, 1, 1, 1 }, { 1, 1, 1, 1 }, { 1, 1, 1, 1 }, { 1, 1, 1, 1 }, { 1, 1, 1, 1 } };
int[][] iJagged1 = iRect1.AsJagged();
int[] lengths = { 3, 5 };
int[] lowerBounds = { 7, 8 };
int[,] iRect2 = (int[,])Array.CreateInstance(typeof(int), lengths, lowerBounds);
int[][] iJagged2 = iRect2.AsJagged();
}
好奇Buffer.BlockCopy()是否可以工作或更快?
编辑: AsJagged 需要处理引用类型。
编辑:在 AsJagged() 中发现错误。添加int l
; 并添加col1 + width
到内循环。