So 事实证明并非所有数组都是一样的。多维数组可以具有非零下界。例如,请参阅 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
到内循环。