[英]C# rows of multi-dimensional arrays
在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?)感谢您的帮助!
你不能传递一行矩形数组,你必须使用锯齿状数组(数组数组):
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)
你没有这样的矩形阵列 。 这是一个单一的对象。
相反,你需要使用锯齿状数组 ,如下所示:
// 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]);
}
请注意,不需要通过引用1传递foo[i]
,并且最好在声明时分配局部变量值,如果可以的话。 (它使您的代码更紧凑,更易于理解。)
1如果您对此不确定,可能需要阅读我在C#中传递参数的文章。
更新 :正如Jon Skeet正确指出的那样,这不提供对该行的引用 ,而是创建一个新副本。 如果您的代码需要更改行,则此方法不起作用。 我已经重命名了这个方法,以明确这一点。
更新2 :如果您希望能够编辑字段,并且也对父数组进行了更改,则可以使用我在此库中提供的包装器。 生成的行foo.Row(i)
不是数组,而是实现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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.