use*_*993 3 c# return-value parameter-passing multidimensional-array
我有一个2D数组,我随机填充数字.我为此工作的代码很好,但是,为了更好地组织我的代码,我想把"随机填充数字"部分放入方法中.
该数组是从Main()方法创建的,因为我计划传递数组并将数组返回到其他将操纵它的方法.然后我尝试编写填充数组的方法,但我不确定如何传递多维数组,或者返回一个数组.根据MSDN,我需要使用"out"而不是返回.
这是我到目前为止所尝试的:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
这些是我的错误:
"The best overloaded method match for 'ProcGen.Program.RandomFill(out int[*,*], int, int)' has some invalid arguments"
"Argument 1: cannot convert from 'int' to 'out int[*,*]'"
Run Code Online (Sandbox Code Playgroud)
我做错了什么,我该怎么做才能解决这些错误?另外,我是正确的思考,因为我正在使用"out",我需要做的就是:
RandomFill(ProcArea[], rows, columns);
Run Code Online (Sandbox Code Playgroud)
代替?:
ProcArea = RandomFill(ProcArea[], rows, columns);
Run Code Online (Sandbox Code Playgroud)
有没有正确的方法来调用方法?
代码中不需要输出参数.
数组passed by references直到你的方法initialise it with new reference.
所以在你的方法中,don't initialise it with new reference你可以不使用out参数和values will be reflected in an original array-
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.
.........
}
Run Code Online (Sandbox Code Playgroud)