C#传递和返回多维数组
我有一个2D数组,我用数字随机填充。我的代码很好用,但是,为了更好地组织我的代码,我想把“用数字随机填充”部分放到一个方法中 数组是从Main()方法创建的,因为我计划将数组传递给/从其他将操作它的方法返回数组。然后我尝试编写填充数组的方法,但我不确定如何传递多维数组,或者返回多维数组。根据MSDN,我需要使用“out”而不是return 这就是我迄今为止所尝试的:C#传递和返回多维数组,c#,multidimensional-array,parameter-passing,return-value,C#,Multidimensional Array,Parameter Passing,Return Value,我有一个2D数组,我用数字随机填充。我的代码很好用,但是,为了更好地组织我的代码,我想把“用数字随机填充”部分放到一个方法中 数组是从Main()方法创建的,因为我计划将数组传递给/从其他将操作它的方法返回数组。然后我尝试编写填充数组的方法,但我不确定如何传递多维数组,或者返回多维数组。根据MSDN,我需要使用“out”而不是return 这就是我迄今为止所尝试的: static void Main(string[] args) { int rows =
static void Main(string[] args)
{
int rows = 30;
int columns = 80;
int[,] ProcArea = new int[rows, columns];
RandomFill(ProcArea[], rows, columns);
}
public static void RandomFill(out int[,] array, int rows, int columns)
{
array = new int[rows, columns];
Random rand = new Random();
//Fill randomly
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < columns; c++)
{
if (rand.NextDouble() < 0.55)
{
array[r, c] = 1;
}
else
{
array[r, c] = 0;
}
}
}
我做错了什么?我能做些什么来修复这些错误?另外,我的想法正确吗,因为我使用的是“out”,我需要做的就是:
RandomFill(ProcArea[], rows, columns);
而不是
ProcArea = RandomFill(ProcArea[], rows, columns);
是否有适当的方法调用该方法?Out参数也需要在调用者端显式指定为
Out
:
RandomFill(out ProcArea[], rows, columns);
尝试:
代码中不需要out参数
数组通过引用传递,直到在方法中使用新引用对其进行初始化
因此,在您的方法中,如果不使用新引用初始化它,则可以不使用out
参数,值将反映在原始数组中-
public static void RandomFill(int[,] array, int rows, int columns)
{
array = new int[rows, columns]; // <--- Remove this line since this array
// is already initialised prior of calling
// this method.
.........
}
publicstaticvoidrandomfill(int[,]数组,int行,int列)
{
array=newint[rows,columns];//试试看……它可以工作:)
使用系统;
阶级制度
{
静态void Main(字符串[]参数)
{
int行=5;
int列=5;
int[,]ProcArea=新int[行,列];
随机填充(填写区域、行、列);
//以5x5格式显示新矩阵
int i,j;
对于(i=0;i
RandomFill(out ProcArea, rows, columns);
public static void RandomFill(int[,] array, int rows, int columns)
{
array = new int[rows, columns]; // <--- Remove this line since this array
// is already initialised prior of calling
// this method.
.........
}
using System;
class system
{
static void Main(string[] args)
{
int rows = 5;
int columns = 5;
int[,] ProcArea = new int[rows, columns];
RandomFill(out ProcArea, rows, columns);
// display new matrix in 5x5 form
int i, j;
for (i = 0; i < rows; i++)
{
for (j = 0; j < columns; j++)
Console.Write("{0}\t", ProcArea[i, j]);
Console.WriteLine();
}
Console.ReadKey();
}
public static void RandomFill(out int[,] array, int rows, int columns)
{
array = new int[rows, columns];
Random rand = new Random();
//Fill randomly
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < columns; c++)
{
if (rand.NextDouble() < 0.55)
{
array[r, c] = 1;
}
else
{
array[r, c] = 0;
}
}
}
}
}