如何引用C#中type[,]类型二维数组的内部数组?
解决二维矩形数组无法直接获取行引用的问题
你用type[,]声明的是矩形数组(Multidimensional Array),它在内存里是一块连续的整块区域,并不是真正的“数组的数组”——所以不存在单独的“内部数组”对象,自然没法通过array[index]直接拿到某一行的引用。
要实现你想要的“直接操作内部数组”的需求,有两种常用方案:
方案1:改用交错数组(Jagged Array)
交错数组是真正的“数组的数组”,每个元素都是独立的一维数组,完全支持直接获取某一行的引用。
声明和初始化示例:
// 声明一个n行n列的交错数组 type[][] array = new type[n][]; // 初始化每一行的一维数组 for (int i = 0; i < n; i++) { array[i] = new type[n]; }
之后你就可以直接操作任意一行:
// 对第0行排序 Array.Sort(array[0]); // 将第1行作为参数传入需要一维数组的函数 SomeFunctionThatTakesArray(array[1]);
方案2:如果必须保留矩形数组
如果你因为现有代码依赖、性能需求(矩形数组内存连续,访问更快)等原因必须用type[,],那只能通过手动复制或者封装访问的方式来模拟“行引用”:
方式A:临时复制行数据
把目标行的数据复制到一个新的一维数组,操作完成后再写回原数组:
int targetRow = 0; int colCount = array.GetLength(1); type[] rowData = new type[colCount]; // 复制行数据 for (int col = 0; col < colCount; col++) { rowData[col] = array[targetRow, col]; } // 对临时数组排序 Array.Sort(rowData); // 写回原数组 for (int col = 0; col < colCount; col++) { array[targetRow, col] = rowData[col]; }
方式B:封装行访问类
写一个简单的包装类,把矩形数组的某一行封装成类似一维数组的结构,这样可以直接通过索引访问原数组的行元素,避免频繁复制:
public class RowAccessor<T> { private readonly T[,] _sourceArray; private readonly int _rowIndex; public int Length => _sourceArray.GetLength(1); public RowAccessor(T[,] sourceArray, int rowIndex) { _sourceArray = sourceArray; _rowIndex = rowIndex; } public T this[int columnIndex] { get => _sourceArray[_rowIndex, columnIndex]; set => _sourceArray[_rowIndex, columnIndex] = value; } }
使用示例:
// 封装第0行 var rowAccessor = new RowAccessor<type>(array, 0); // 可以像操作一维数组一样访问元素 rowAccessor[2] = someValue; // 如果需要排序,还是得先转成临时数组再写回 type[] temp = new type[rowAccessor.Length]; for (int i = 0; i < temp.Length; i++) { temp[i] = rowAccessor[i]; } Array.Sort(temp); for (int i = 0; i < temp.Length; i++) { rowAccessor[i] = temp[i]; }
内容的提问来源于stack exchange,提问作者vy8
相关产品推荐
相关产品推荐

