在C#中如何将多维数组中的子数组传递给函数?
问题本质
你用的int[,,]是C#里的多维矩形数组,这种数组的每一个元素都是单个int值,所以访问时必须指定三个维度的索引(比如threeDArr[1,2,0]才能拿到16)。你以为传两个索引能拿到子数组,是把它和交错数组(int[][][],嵌套的一维数组)搞混了。
解决方案
方案1:改用交错数组
把数组定义改成嵌套的交错数组,这样每个层级的元素都是数组,传两个索引就能拿到一维数组(注意C#不允许变量名以数字开头,已修正变量名):
public void function(int[] arr) { // 执行操作 } static void Main(string[] args) { int[][][] threeDArr = { new int[][] { new int[] {1,2,3}, new int[] {4,5,6}, new int[] {7,8,9} }, new int[][] { new int[] {10,11,12}, new int[] {13,14,15}, new int[] {16,17,18} } }; function(threeDArr[1][2]); // 这里拿到的是{16,17,18}这个一维数组,符合函数参数要求 }
交错数组的访问方式是用连续的方括号[x][y],而非多维数组的逗号分隔[x,y]。
方案2:从多维数组手动提取子数组
如果必须保留多维数组的结构,需要手动遍历目标维度的所有元素,组装成一维数组再传入函数:
public void function(int[] arr) { // 执行操作 } static void Main(string[] args) { int[,,] threeDArr = {{{1,2,3}, {4,5,6}, {7,8,9}}, {{10,11,12}, {13,14,15}, {16,17,18}}}; // 提取threeDArr[1,2, *]对应的所有元素 int[] subArr = new int[threeDArr.GetLength(2)]; for (int i = 0; i < threeDArr.GetLength(2); i++) { subArr[i] = threeDArr[1, 2, i]; } function(subArr); // 传入组装好的一维数组 }
这里用GetLength(2)获取第三个维度的长度(避免硬编码数字),循环把对应位置的元素存入新数组。
内容的提问来源于stack exchange,提问作者Insert0Name0Here
相关产品推荐
相关产品推荐

