在C#中,有没有一种方法可以从多维数组中获取一个数组?

3
function(int[] me)
{
    //Whatever
}

main()
{
    int[,] numbers = new int[3, 2] { {1, 2}, {3, 4}, {5, 6} };    
    function(numbers[1]);
}

我想把 int[] {3,4} 传递给函数,但这样做不起作用。有没有办法实现这个需求?


有点令人困惑的问题... - Stan R.
5个回答

2

0

int[] {3,4} 指的是一个位置,而不是一个数组,并且保存了一个整数。你的函数应该是

function(int me)
{
    //Whatever
}

这是如何获取值并传递给您的函数的方法

    int valueFromLocation = numbers[3,4];

    function(valueFromLocation )
    {
        //Whatever
    }

编辑:

如果您在任何情况下都需要整个数组,请使用交错数组。

int[][] jaggedArray =
     new int[2][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };

int[] array1 =  jaggedArray[1];
int[] array1 =  jaggedArray[2];

现在你可以按照自己的方式传递它

function(int[] array){}

他想传递一个 int[],这就是问题。 - John Boker
谢谢,"int[] {3,4}" 确实有点困惑。我已经修正了我的答案。 - Asad

0

不,你不能这样做,但你可以自己转换。就像这样。

 int[,] numbers = new int[3, 2] { {1, 2}, {3, 4}, {8, 6} };

           List<int[]> arrays = new List<int[]>();
           for (int i = 0; i < 3; i++)
           {
               int[] arr = new int[2];
               for (int k = 0; k < 2; k++)
               {
                   arr[k] = numbers[i, k];
               }

               arrays.Add(arr);
           }

           int[] newArray = arrays[1]; //will give int[] { 3, 4}

我想我太过于字面理解这个问题了,是吗? - Stan R.

0
function(int[] me) 
{ 
    //Whatever 
} 

main() 
{ 
    int[][] numbers = new int[3][] { new int[2] {1, 2}, new int[2]{3, 4}, new int[2] {5, 6} };     
    function(numbers[1]); 
} 

这被称为不规则数组(数组的数组)。如果您无法更改数字的定义,则需要编写一个可以执行此操作的函数


0
也许可以使用 function(new int[] { 3, 4 });?如果您写下一个实际的问题,这会有所帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接