8

在C#编程语言中,如何传递一行多维数组?例如,假设我有以下内容:

int[,] foo;
foo = new int[6,4];
int[] least;
least = new int[6];

for(int i = 0; i < 6; i++)
{
    least[i] = FindLeast(ref foo[i]);     //How do I pass the ith row of foo???
}

另外,谁能向我解释在 C# 中使用矩形和锯齿状数组的好处?这是否发生在其他流行的编程语言中?(Java?)感谢所有帮助!

4

3 回答 3

8

你不能传递一行矩形数组,你必须使用一个锯齿状数组(数组的数组):

int[][] foo = new int[6][];

for(int i = 0; i < 6; i++)
    foo[i] = new int[4];

int[] least = new int[6];

for(int i = 0; i < 6; i++)
    least[i] = FindLeast(foo[i]);

编辑
如果您发现使用锯齿状数组非常烦人并且迫切需要一个矩形数组,那么一个简单的技巧可以拯救您:

int FindLeast(int[,] rectangularArray, int row)
于 2012-03-06T19:07:24.060 回答
4

你没有,像这样的矩形阵列。这是一个单一的对象。

相反,您需要使用锯齿状数组,如下所示:

// Note: new int[6][4] will not compile
int[][] foo = new int[6][];
for (int i = 0; i < foo.Length; i++) {
    foo[i] = new int[4];
}

然后你可以传递每个“子”数组:

int[] least = new int[foo.Length];
for(int i = 0; i < 6; i++)
{
    least[i] = FindLeast(foo[i]);
}

请注意,不需要foo[i]通过引用1传递,并且在声明时分配局部变量值也是一个好主意,如果可以的话。(它使您的代码更紧凑,更易于理解。)


1如果您对此不确定,您可能需要阅读我关于C# 中的参数传递的文章。

于 2012-03-06T19:06:37.553 回答
-1

更新:正如 Jon Skeet 正确指出的那样,这不提供对该行的引用,而是创建一个新副本。如果您的代码需要更改一行,则此方法不起作用。我已重命名该方法以明确这一点。

更新 2:如果您希望能够编辑字段,并且对父数组也进行更改,您可以使用我在这个库中提供的包装器 I maed。结果行foo.Row(i)不是数组,而是 implements IList,因此如果您需要传递数组,这也不是解决方案。


此扩展方法将允许您查询多维数组的行。应该注意的是,这计算量很大(效率高),如果可能的话,您应该在这些情况下使用锯齿状数组。但是,如果您发现自己无法使用锯齿状数组,这可能会很有用。

public static T[] CopyRow<T>(this T[,] arr, int row)
{
    if (row > arr.GetLength(0))
        throw new ArgumentOutOfRangeException("No such row in array.", "row");

    var result = new T[arr.GetLength(1)];
    for (int i = 0; i < result.Length; i++)
    {
        result[i] = arr[row, i];
    }
    return result;
}

您的代码现在可以重写:

int[,] foo;
foo = new int[6,4];
int[] least;
least = new int[6];

for(int i = 0; i < 6; i++)
{
    least[i] = FindLeast(ref foo.CopyRow(i));
}
于 2014-05-02T13:49:17.360 回答